Python の組み込み関数のデコレーター、スタティックメソッド @staticmethod の『使用例』と『エラー例』です。
(Python) @staticmethod
(スタティックメソッド)
(Python) クラス定義(『プログラマのための注釈: クラス定義内で定義された変数はクラス属性であり、全てのインスタンス間で共有されます。』)
(Python) parameter
(パラメーター、仮引数(かりひきすう)、引数)
(Python) class variable
(クラス変数)
暗黙の引数は無かった
スタティックメソッド staticmethod には、暗黙の引数がありませんでした。
スタティックメソッドは、クラス名からも呼べましたし、インスタンスオブジェクト obj から呼ぶこともできました。
class MyClass:
@staticmethod
def method():
return '-- staticmethod called --'
MyClass.method()
'-- staticmethod called --'
class MyClass:
@staticmethod
def method():
return '-- staticmethod called --'
obj = MyClass()
obj.method()
'-- staticmethod called --'
普通の関数のように使えた
スタティックメソッドは、普通の関数のように、使いたい引数だけを書けば使えました。
class MyClass:
@staticmethod
def method(value):
return value + 111
MyClass.method(500)
611
class MyClass:
@staticmethod
def method(value):
return value + 111
obj = MyClass()
obj.method(500)
611
インスタンス変数は参照できなかった
スタティックメソッドの中からは、インスタンス変数を参照することができませんでした。
インスタンスオブジェクト self を受け取ろうとしても、『暗黙の引数』が無いので、エラーになりました。
class MyClass:
def __init__(self, value):
self.instance_variable = value
return
@staticmethod
def method(self):
return
obj = MyClass(500)
obj.method()
Traceback (most recent call last):
...
TypeError: method() missing 1 required positional argument: 'self'
クラス変数は参照できた
スタティックメソッドの中では、クラス変数が参照できました。
class MyClass:
class_variable = 500
@staticmethod
def method():
return MyClass.class_variable
a = MyClass()
b = MyClass()
MyClass.class_variable
500
a.method()
500
a.class_variable
500
b.method()
500
b.class_variable
500
クラス変数の値を変更したら『作成済みのインスタンス』が影響を受けた
インスタンスを作ったあとに、クラス変数の値を変えたら、既存のインスタンスから参照したクラス変数の値も変わっていました。
すべてのインスタンスから、共通の変数を参照したいときに、便利そうでした。
class MyClass:
class_variable = 500
@staticmethod
def method():
return MyClass.class_variable
a = MyClass()
b = MyClass()
MyClass.class_variable += 111
MyClass.class_variable
611
a.method()
611
a.class_variable
611
b.method()
611
b.class_variable
611