출처: https://meyouus.tistory.com/64 [정보 공유 - For Me For You For Us]
본문으로 바로가기

이번에는 staticmethod, classmethod, instancemethod 이 세가지의 차이에 대해서 써보도록 하겠다.

Instance Method

우선 instancemethod부터 보자. 사실 이는 우리가 Django나 참조하는 다른 함수들에서 볼 수 있는 흔한 메소드이다.

class InstanceMethod:
    def __init__(self):
        self.type = 'Instance Method'
    def print_type(self):
        print(f'This is an {self.type}')

>>> isntance = InstanceMethod()
>>> instance.print_name()
This is an Instance Type

Instance Method의 경우, 메소드 안의 함수를 호출해내기 위해서는, instance를 항상 먼저 정의를 해주어야 한다. 만약 그렇게 하지 않는다면 오류가 난다:

>>> InstanceMethod().print_name()    # AttributeError: 'InstanceMethod' object has no attribute 'print_name'



Class Method

이번에는 class method를 보도록 하자. Class MethodInstance Method의 결정적인 차이는 인스턴스 또는 클래스를 따로 선언해주지 않아도 된다는 것에 있다. 다음을 보자:

class ClassMethod:
    @classmethod
    def print_type(cls):
        print(f'This is a {cls.__class__.__name__}')

>>> ClassMethod.print_type()
This is a type

이것을 보면 Class Method의 경우는 저절로 클래스 자기 자신을 전달받는 것을 알 수 있다. 여기서 cls를 써주는 것은 파이썬 PEP8에 정의된 Python Convention이다.


Static Method

마지막으로 static method를 한번 보자. static method는 위의 두 메서드와 다른 점은 instance나 클래스 둘 다 따로 전달받거나 정의하지 않아도 된다:

class StaticMethod:
    @staticmethod
    def print_type(type):
        print(f'This is a {type}')

>>> StaticMethod.print_type('Static Method') #  클래스를 전달 받았을 경우
This is a Static Method
>>> instance = StaticMethod() # 인스턴스로 전달 받았을 경우
>>> instance.print_type('Static Method')
This is a Static Method

Static Method는 일반적인 함수와 똑같이 작동하지만, 인스턴스나 클래스를 전달받지 못하는 것을 볼 수 있고, 모든 클래스/인스턴스에 포함되는 함수인 것 또한 알 수 있다. (전달은 받지 않지만, 포함은 되어 있다)


요약

여기에서 잘 요약한 부분을 발췌해봤다:

class MyClass:
    def method(self):
        return 'instance method called', self

    @classmethod
    def classmethod(cls):
        return 'class method called', cls

    @staticmethod
    def staticmethod():
        return 'static method called'

>>> instance = MyClass()
>>> instance.method()
('instance method called', <__main__.MyClass object at 0x000001FEC7E46220>)
>>> instance.classmethod()
('class method called', <class '__main__.MyClass'>)
>>> instance.staticmethod()
'static method called'

위의 두 method(), classmethod()는 각각 인스턴스와 클래스를 전달받는 것을 알 수 있다. 하지만 staticmethod()의 경우, MyClass 클래스의 instance에 포함되어 있으면서도, 인스턴스나 클래스를 전달받지 않고, 클래스 내부에 정의해둔 함수를 그대로 불러오는 것을 볼 수 있다.