鉴于代码:
class Character():
def __init__(self, name):
self.name = name
self.health = 50
self.damage = 10
class Warrior(Character):
def __init__(self, name, weapon, armor):
super(Character).__init__()
self.weapon = weapon
self.armor = armor
self.strength = 10
self.dexterity = 5
self.intelligence = 5
Doug = Character("Doug")
Mark = Warrior("Mark", "Axe", None)
Warrior
类为什么不从health
类继承Character
?
为了能够打印Mark.health
,我需要做些什么?
答案 0 :(得分:4)
您错误地使用了super()
;不要单独传递Character
。在Python 3中,根本不传递任何内容,但确实将name
传递给__init__
:
class Warrior(Character):
def __init__(self, name, weapon, armor):
super().__init__(name)
self.weapon = weapon
self.armor = armor
self.strength = 10
self.dexterity = 5
self.intelligence = 5
现在,属性设置正确,包括health
和damage
:
>>> Mark = Warrior("Mark", "Axe", None)
>>> vars(Mark)
{'name': 'Mark', 'health': 50, 'damage': 10, 'weapon': 'Axe', 'armor': None, 'strength': 10, 'dexterity': 5, 'intelligence': 5}
在幕后,super(Character).__init__()
最终调用super.__init__()
方法,该方法在类的方法中恰好起作用但不产生任何实际用途(返回None
)。< / p>