关于继承和super()

时间:2017-03-19 11:38:50

标签: python python-3.x class inheritance super

鉴于代码:

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,我需要做些什么?

1 个答案:

答案 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

现在,属性设置正确,包括healthdamage

>>> 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>