[英]Python metaprogramming update class A every time class B changes
class Base:
def __init__(self):
self.x = 4
class C1(Base):
...
class C2(Base):
...
obj1 = C1()
obj2 = C2()
obj1.x = 2
我了解“ Singletons”,如果我更改C1的“ self.x”,它可以自動更新該單個類的每個實例的“ self.x” ...但是我將如何使用相同的庫更新所有類?
將x聲明移出init:
class Base:
x = 4
def __init__(self):
稍后,當您需要設置它時,請執行以下操作:
Base.x = 5
您可以將其包裝到@staticmethod
以使其更容易。
正如其他人提到的那樣,靜態變量確實很糟糕,除非您是最后的選擇,否則不應該使用它們。
如果我錯了,請有人糾正我,但是可以使用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描述符的對象都將始終返回該值,我不確定是否可以提供幫助,但這就是我理解問題的方式,您甚至不需要基類,但是您可以
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.