次のコードがある場合:
class Foo(object):
bar = 1
def bah(self):
print(bar)
f = Foo()
f.bah()
文句を言う
NameError: グローバル名 'bar' が定義されていません
bar
メソッド内でクラス/静的変数にアクセスするにはどうすればよいbah
ですか?
次のコードがある場合:
class Foo(object):
bar = 1
def bah(self):
print(bar)
f = Foo()
f.bah()
文句を言う
NameError: グローバル名 'bar' が定義されていません
bar
メソッド内でクラス/静的変数にアクセスするにはどうすればよいbah
ですか?
またはをbar
使用する代わりに。に割り当てると静的変数が作成され、に割り当てるとインスタンス変数が作成されます。self.bar
Foo.bar
Foo.bar
self.bar
クラスメソッドを定義します。
class Foo(object):
bar = 1
@classmethod
def bah(cls):
print cls.bar
これで、bah()
インスタンスメソッドである必要がある場合(つまり、selfにアクセスできる場合)でも、クラス変数に直接アクセスできます。
class Foo(object):
bar = 1
def bah(self):
print self.bar
class Foo(object):
bar = 1
def bah(self):
print Foo.bar
f = Foo()
f.bah()