我有一堂課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幾乎不反對封裝。我應該如何設計這些事件,以使它們遵循封裝并通常更有意義?
添加回答
舉報
0/150
提交
取消