【发布时间】:2020-05-23 16:45:46
【问题描述】:
我必须模拟一个战士以及他可以执行的不同类型的攻击。这个想法是使用 mixins 来包含攻击逻辑。我的类是通过以下方式定义的:
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?
【问题讨论】:
-
所有在这种情况下
__init__方法应该使用super()。 -
属性并不真正属于类;它们都属于同一个实例,但只有在调用设置它们的
__init__方法时才会创建每个实例。
标签: python python-3.x oop inheritance mixins