파이썬 @classmethod와 @staticmethod 차이

이동욱

2021/03/03

Categories: 프로그래밍 - 파이썬 Tags: 파이썬 플라스크

파이썬을 코딩을 하다가 @classmethod 데코레이터가 붙어 있는 메서드를 볼 수 있었다. 정확히 어떤 역할을 하는지 몰라서 문서에서 찾아보았다.

@classmethod

Screen Shot 2021-03-03 at 8 48 29 AM

클래스 메서드는 다음과 같이 사용한다.

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

여기까지만 봐서는 정적 메서드랑 무슨 차이인지 알기 힘들었다. 따라서 정적 메서드 관련된 문서를 확인해봤다.

@staticmethod

Screen Shot 2021-03-03 at 9 09 51 AM

사용하는 방법은 다음과 같다.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...
class C:
    builtin_open = staticmethod(open)

차이점

얼핏봐서는 차이점을 크게 못느껴서 인터넷을 찾아본 결과 좋은 글을 볼 수 있었다. 3

@classmethod@staticmethod는 상속에서 차이가 난다.

class Person:
    default= "아빠"

     def __init__(self):
        self.data = self.default

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

    @staticmethod
    def static_person():
        return Person()

class WhatPerson(Person):
    default = "엄마"
person1 = WhatPerson.class_person()    # return 엄마
person2 = WhatPerson.static_person()   # return 아빠

위와 같이 @staticmethod인 경우에는 부모 클래스의 속성 값을 가져오지만, @classmethod의 경우 cls 인자를 활용하여 클래스의 클래스 속성을 가져온다.

참고 문헌


  1. https://docs.python.org/3/library/functions.html#classmethod ↩︎

  2. https://docs.python.org/3/library/functions.html#staticmethod ↩︎

  3. https://medium.com/@hckcksrl/python-%EC%A0%95%EC%A0%81%EB%A9%94%EC%86%8C%EB%93%9C-staticmethod-%EC%99%80-classmethod-6721b0977372 ↩︎

>> Home