본문 바로가기

Python

[Python] @staticmethod vs @classmethod

@staticmethod

  • 클래스 내부에서 데코레이터를 통해 사용
  • self 인자를 갖고 있지 않음, 이로인해 클래스 객체를 선언하지 않고 직접 접근 가능함. ex)Test.static_function()

@classmethod

  • 클래스 내부에서 데코레이터를 통해 사용
  • self 대신 cls 인자를 갖고 있음, staticmethod와 마찬가지로 클래스 객체를 선언하지 않고 직접 접근 가능함. ex) Test.class_function()
  • 상속에서 차이가 남.(코드 예시 확인)

 

코드 예시

class Test:
    name = "Test"

    @staticmethod
    def static_function():
        return Test.name

    @classmethod
    def class_function(cls):
        return cls.name


class Test2(Test):
    name = "Test2"

if __name__ == "__main__":
    print(Test.static_function()) # Test 출력
    print(Test2.static_function()) # Test 출력
    print(Test.class_function()) # Test 출력
    print(Test2.class_function()) # Test2 출력

 

'Python' 카테고리의 다른 글

[Python] GIL(Global Interpreter Lock)  (0) 2021.03.16
[Python]ABC(Abstract Base Class)  (0) 2021.03.11
[Python] django vs flask  (0) 2021.03.11
[Python] is vs ==  (0) 2021.03.01
[Python] requests 라이브러리  (0) 2020.09.01