Мне нужно смоделировать воина и различные виды атак, которые он может выполнить. Идея состоит в том, чтобы использовать миксины для хранения логики атаки c. Мои классы определены следующим образом:
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
(при вызове self.attack()
внутри sword_spin()
метода HandToHandCombatMixin
класс) принадлежит классу TemplarKnight
вместо HandToHandCombatMixin
.
Как мне написать этот код, чтобы Python искал self.attacks_cost
внутри HandToHandCombatMixin
?