在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
謝謝,非常好 – 2012-07-27 12:11:43
@ChZeeshan:不客氣。 – Tadeck 2012-07-27 12:13:08