Colorful Wires

エンジニアリングの勉強の記録

classmethod と staticmethod の使い分け

static method は、selfcls にアクセスできないので、同じクラス内の別のメソッドを呼ぶことができません。 class method は、cls 経由で自分のクラス自身にアクセスできるので、これが可能です。

以下に例を示します。

class MyClass1:
    @staticmethod
    def static_func():
        self.another_static_func()

    @staticmethod
    def another_static_func():
        print("another")

class MyClass2:
    @classmethod
    def class_func(cls):
        cls.another_static_func()

    @staticmethod
    def another_static_func():
        print("another")


# mc = MyClass1()
# mc.static_func()

# 実行結果
# >>>  Traceback (most recent call last):
#  File "prog.py", line 21, in <module>
#    mc.static_func()
#  File "prog.py", line 4, in static_func
#    self.another_static_func()
# NameError: name 'self' is not defined

mc = MyClass2()
mc.class_func()

# 実行結果
# >>> another