我有一个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
。这使它有些复杂,我必须将其attacker
作为参数提供给hurt()
-method,然后再次引发attacker
invictim
的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)
我认为我什至不应该attacker
作为hurt()
-method 的参数,因为它不需要伤害,只需要引发事件。此外,event_kill
在受害者的- 方法中引发攻击者的 - 事件hurt()
几乎不反对封装。
我应该如何设计这些事件,以便它们遵循封装并且通常更有意义?