【发布时间】:2020-11-27 10:14:15
【问题描述】:
我在 Python 中练习多重继承。
没有Boss 类,一切顺利。非常感谢任何帮助。
我提到过:How does Python's super() work with multiple inheritance?
反馈:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
41 print(archer1.__str__())
42 print('')
---> 43 boss = Boss("Boss", 50, 50, 100)
44 print(boss.__str__())
in __init__(self, name, power, agility, HP)
27 class Boss(Worrior,Archer):
28 def __init__(self, name, power, agility, HP):
---> 29 Worrior.__init__(self, name, power, HP)
30 Archer.__init__(self, name, agility, HP)
31 def __str__(self):
in __init__(self, name, power, HP)
7 class Worrior(Player):
8 def __init__(self, name, power, HP):
----> 9 super().__init__(HP)
10 self.name = name
11 self.power = power
TypeError: __init__() missing 2 required positional arguments: 'agility' and 'HP'
好像取了Worrior类里面的power属性,然后就停了。
class Player:
def __init__(self,HP):
self.HP = HP
def sign_in(self):
print('player sign in')
# put the class want to extend from
class Worrior(Player):
def __init__(self, name, power, HP):
super().__init__(HP)
self.name = name
self.power = power
# it's the toString() method in java
# need to override the dunder(magic) method
def __str__(self):
return "The worrior's name: " f'{self.name} \n' \
"He has the power:" f'{self.power}'
class Archer(Player):
def __init__(self, name, agility, HP):
super().__init__(HP)
self.name = name
self.agility = agility
def __str__(self):
return "The archer's name: " f'{self.name} \n' \
"He has the agility:" f'{self.agility}'
class Boss(Worrior,Archer):
def __init__(self, name, power, agility, HP):
Worrior.__init__(self, name, power, HP)
Archer.__init__(self, name, agility, HP)
def __str__(self):
return "The boss's name: " f'{self.name} \n' \
"With Worrior's power " f'{self.power} \n' \
"and With Archer's agilit" f'{self.agility}'\
"The boss' HP is: " f'{self.HP}'
boss = Boss("Boss", 50, 50, 100)
print(boss.__str__())
【问题讨论】:
-
@ThierryLathuille 解决了订单问题,这是一篇非常好的帖子,但它没有解决如何处理构造函数的签名从类到类的变化(就像这里一样)
标签: python multiple-inheritance super