我有一個類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()
- 方法,然後再籌集victim
的hurt()
- 方法的attacker
事件:
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()
-方法的參數,因爲它不需要傷害,僅用於提高事件。 此外,提高攻擊者的event_kill
-受害者內部的事件hurt()
-方法很難對抗封裝。
我應該如何設計這些事件以便他們遵循封裝並且通常更有意義?
他們需要是類方法嗎? – James
'他們'?聽衆不會,他們可以是任何東西。但顯然它是攻擊者和受到傷害的人,所以'攻擊'和'傷害'必須是方法。 –
對當天最有趣的問題標題+1。 – Alfe