gpt4 book ai didi

python - 当通过组合关联对象时,使用什么模式来促进对象之间的通信

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:52 25 4
gpt4 key购买 nike

假设我有一个 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 Catcontainer 对象>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

关于python - 当通过组合关联对象时,使用什么模式来促进对象之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57549238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com