我必须模拟一个战士和他可以执行的不同类型的攻击。其思想是使用mixin来包含攻击逻辑。我用以下方式定义了我的类:
class Warrior:
def __init__(self, energy):
self.energy = energy
class TemplarKnight(Warrior, HandToHandCombatMixin):
pass
class CombatMixin:
def __init__(self):
self.attacks_cost = {}
def attack(self, attacker, attack_cost):
if attacker.energy < attack_cost:
print('Not enough energy to attack')
else:
attacker.energy -= attack_cost
print('Attack!')
class HandToHandCombatMixin(CombatMixin):
def __init__(self):
super().__init__()
self.attacks_cost['sword_spin'] = 10
def sword_spin(self, attacker):
return self.attack(attacker, self.attacks_cost['sword_spin'])
但是当我尝试测试这个设置时,问题就出现了。当我这样做的时候
class TestTemplarKnight(unittest.TestCase):
def setUp(self):
self.templar = TemplarKnight(energy=100)
def test_templar_knight_can_sword_spin(self):
self.templar.sword_spin(self.warrior)
self.assertEquals(self.templar.energy, 90)
我明白了
def sword_spin(self, attacker):
return self.attack(
> attacker, self.attacks_cost['sword_spin'])
E AttributeError: 'TemplarKnight' object has no attribute 'attacks_cost'
Python似乎认为参数self.attacks_cost
(在HandToHandCombatMixin
类的sword_spin()
方法内调用self.attack()
)属于TemplarKnight
类,而不是HandToHandCombatMixin
我应该如何编写这段代码使Python在HandToHandCombatMixin
中查找self.attacks_cost
要正确使用
super
,所有涉及的类都需要使用它。现在,首先调用Warrior.__init__
,但它不使用super
,因此HandToHandCombatMixin.__init__
永远不会被调用添加以下内容:
现在,当您实例化
TemplarKnight
时,您将保证以正确的顺序调用所有__init__
方法。最终,对super()
的一次调用将导致object.__init__
被调用,在这一点上链最终结束。如果正确处理关键字参数,**kwargs
在发生时将为空相关问题 更多 >
编程相关推荐