Pythonには静的変数はありませんが、そのためにクラス変数を使用できます。次に例を示します。
class MyClass(object):
x = 0
def __init__(self, x=None):
if x:
MyClass.x = x
def do_something(self):
print "x:", self.x
c1 = MyClass()
c1.do_something()
>> x: 0
c2 = MyClass(10)
c2.do_something()
>> x: 10
c3 = MyClass()
c3.do_something()
>> x: 10
を呼び出すとself.x
、最初にインスタンスレベルの変数が検索されself.x
、としてインスタンス化されます。見つからない場合は、が検索されClass.x
ます。したがって、クラスレベルで定義できますが、インスタンスレベルでオーバーライドできます。
広く使用されている例は、インスタンスへのオーバーライドが可能なデフォルトのクラス変数を使用することです。
class MyClass(object):
x = 0
def __init__(self, x=None):
self.x = x or MyClass.x
def do_something(self):
print "x:", self.x
c1 = MyClass()
c1.do_something()
>> x: 0
c2 = MyClass(10)
c2.do_something()
>> x: 10
c3 = MyClass()
c3.do_something()
>> x: 0