有人糾正我,如果我錯了,但是這很容易用一個簡單的reaaaal描述來解決這樣的例子:
class KeepSync(object):
def __init__(self, default):
self.value = default
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = value
class Foo(object):
bar = KeepSync(0)
class C1(Foo):
pass
class C2(Foo):
pass
f = C1()
g = C2()
print "f.bar is %s\ng.bar is %s" % (f.bar, g.bar)
print "Setting f.bar to 10"
f.bar = 10
print "f.bar is %s\ng.bar is %s" % (f.bar, g.bar) # YAY BOTH ARE 10 !
繼承KeepSync描述符將始終返回值的任何對象,我不當然,如果我幫助,但是,這就是我理解問題的方法,你甚至不需要基類,但是你可以使用
如果你在python中使用單例,你通常會做錯事。 – ThiefMaster
你是某種形式的類的「靜態」變量之後: http://stackoverflow.com/questions/68645/static-class-variables-in-python – jozxyqk