본문 바로가기
파이썬

[Python] @staticmethod, @classmethod - 정적메서드를 지원하는 방법

by 책 읽는 개발자_테드 2022. 5. 8.
반응형

· 정적메서드는 인스턴스를 만들지 않아도 class에 직접 접근하여 바로 실행할 수 있는 메서드다. 

· 파이썬에서는 정적메서드를 지원하는 두 가지 방법 @staticmethod, @classmethod가 있다.

 

class calculator:

    @staticmethod
    def add(x, y):
        return x + y

    @classmethod
    def sub(cls, x, y):
        return x - y


print(calculator.add(20, 10))
print(calculator.sub(20, 10))

결과

- @classmethod를 선언한 메서드는 cls라는 인자를 추가해야한다.

- cls는 클래스를 가르킨다. 이것으로 클래스의 어떤 속성에도 접근할 수 있다.

 

class calculator:
    num = 10

    @classmethod
    def sub(cls, x):
        return x - cls.num


print(calculator.sub(20))

결과

 

반응형

댓글