假设我有一个 python 类:Foo(),它有一个成员 self.bar,它在 Foo() 的初始化时被分配为 Bar() 的一个实例。所以像这样:
class Foo:
def __init__(self):
self.bar = Bar()
self.other_member = 0
然后假设我将 Bar() 的某些方法绑定(bind)到信号/回调,当(外部)触发时,我希望它对 Foo() 的其他一些成员进行更改。
我的问题是:想做这件事是不是很疯狂?如果没有,在实现此类操作时是否有可遵循的建议模式?
请您参考如下方法:
你可以使用继承来建立Trait行为,并将新创建的容器对象注册到Trait静态变量.
在这个例子中:
- Parent
class Trait是所有逻辑所在的地方。 - 在继承自
Trait的子类中定义trait特定行为,例如Trait_Meow。 - 使用组合将每个
动物类别与其特征联系起来。 - 您可以使用
(方法) 从.trait事件 (方法) 中引用 class Cat 的container对象>self.animal()
from weakref import WeakSet, ref as weakref
class Trait:
def register_animal(self):
try:
self.__class__.live_animals.add(self)
except AttributeError as e:
self.__class__.live_animals = WeakSet([self])
def __init__(self, animal):
self.animal = weakref(animal)
self.register_animal()
class Trait_Meow(Trait):
def meow(self):
print('{} says: meoooooow'.format(self.animal().name))
def all_meow():
for animal in Trait_Meow.live_animals:
animal.meow()
class Cat:
def __init__(self, name):
self.name = name
self.traits = set([Trait_Meow(self)])
if __name__ == '__main__':
cat1 = Cat('cat1')
cat2 = Cat('cat2')
Trait_Meow.all_meow()
# output
# cat2 says: meoooooow
# cat1 says: meoooooow
