我有一堂课Person,看起来像这样:
class Person(object):
def __init__(self, health, damage):
self.health = health
self.damage = damage
def attack(self, victim):
victim.hurt(self.damage)
def hurt(self, damage):
self.health -= damage
我还有一个Event类,其中包含侦听器函数,这些事件在事件触发时被调用。让我们为实例添加一些事件:
def __init__(self, health, damage):
self.health = health
self.damage = damage
self.event_attack = Event() # fire when person attacks
self.event_hurt = Event() # fire when person takes damage
self.event_kill = Event() # fire when person kills someone
self.event_death = Event() # fire when person dies
现在,我希望我的事件使用来将某些数据发送到侦听器函数**kwargs。问题是,我希望所有四个事件都发送attacker和victim。这使其变得有些复杂,我必须将-methodattacker作为参数提供hurt(),然后再次引发attackerinvictim的hurt()-method的事件:
def attack(self, victim):
self.event_attack.fire(victim=victim, attacker=self)
victim.hurt(self, self.damage)
def hurt(self, attacker, damage):
self.health -= damage
self.event_hurt.fire(attacker=attacker, victim=self)
if self.health <= 0:
attacker.event_kill.fire(attacker=attacker, victim=self)
self.event_death.fire(attacker=attacker, victim=self)
我认为我什至不应该给-methodattacker作为参数hurt(),因为伤害并不需要它,而只是引发事件。另外,event_kill在受害者的hurt()-method中引发攻击者的-event几乎不反对封装。
我应该如何设计这些事件,以使它们遵循封装并通常更有意义?
相关分类