python

Python 정적 메소드 @classmethod, @staticmethod

sklass 2021. 10. 24. 20:02

정적메소드라 함은 클래스에서 직접 접근할 수 있는 메소드입니다. 파이썬에서는 클래스에서 직접 접근할 수 있는 메소드가 두가지 있는데, 그게 바로 @classmethod@staticmethod 입니다. 하지만, 파이썬에서는 다른언어와는 다르게 정적메소드임에도 불구하고 인스턴스에서도 접근이 가능합니다.

class CustomClass:

    # instance method
    def add_instance_method(self, a,b):
        return a + b

    # classmethod
    @classmethod
    def add_class_method(cls, a, b):
        return a + b

    # staticmethod
    @staticmethod
    def add_static_method(a, b):
        return a + b

위의 예제를 보면 알 수 있듯이, instance method는 첫번째 인자로 객체 자신 self 를 입력합니다. classmethod는 첫번째 인자로 cls를, staticmethod는 특별히 추가되는 인자 없이 사용합니다. 

사용법에서 instance method와 classmethod, staticmethod의 차이점은, classmethod나 staticmethod는 객체를 선언하지 않고도 함수를 사용할 수 있다는 것입니다.

아래의 예제를 살펴보겠습니다.

from static_method import CustomClass
# instance method
CustomClass.add_instance_method(None, 3, 5)
>>> 8

# classmethod
CustomClass.add_class_method(3, 5)
>>> 8

# staticmethod
CustomClass.add_static_method(3, 5)
>>> 8

classmethod나 staticmethod는 정적 메소드이지만 파이썬에서는 아래와 같이 객체에서의 접근이 가능합니다.

a = CustomClass()

a.add_class_method(3, 5)
>>> 8

a.add_static_method(3, 5)
>>> 8

@classmethod와 @staticmethod의 차이점

위와 같이 classmethod는 cls라는 인자를 받지만, staticmethod는 아무런 인자를 받지 않는 차이점이 있었습니다. 이 차이점은 상속에서 두드러지게 나타납니다. 아래의 예제를 살펴 보겠습니다.

class Language:
    default_language = "English"

    def __init__(self):
        self.language = default_language

    @classmethod
    def class_my_language(cls):
        return cls()

    @staticmethod
    def static_my_language():
        return Language()

    def __str__(self):
        return self.language


class KoreanLanguage(Language):
    default_language = "Korean"
 
 a = KoreanLanguage.static_my_language()
 b = KoreanLanguage.class_my_language()
 
 print(a)
 >>> "English"
 print(b)
 >>> "Korean"

위의 예제와 같이, staticmethod에서는 부모 클래스의 클래스 속성값을 가져오지만, classmethod에서는 cls의 클래스 속성을 가져오는 것을 알 수 있습니다.