类继承,使用Child Class设置父类

时间:2014-11-20 21:37:10

标签: python class inheritance

我正在尝试更多地学习Python中的Classes,并且正在编写一个程序来帮助解决这个问题。我已经定义了我的Parent Class和Child类,如下所示:

class Character():
'Common base class for all characters'
    def __init__(self):
        self.attack = 1
        self.defence = 1
        self.strength = 1

    def setAttack(self, attack):
        self.attack = attack

    def setDefence(self, defence):
        self.defence = defence

    def setStrength(self, strength):
        self.strength = strength

class Enemy(Character):
    'Enemy Class'
    def __init__(self):
        self.setAttack(random.randint(5,20))
        self.setDefence(random.randint(5,20))
        self.setStrength(random.randint(5,20))

这意味着我可以使用

行来定义敌人
enemy1 = Enemy()

我的观点是我可以用不同的随机值复制敌人类来创建不同类型的敌人。即创建一个与上面相同但具有不同随机值的BiggerEnemy类。

虽然上面的代码有效,但我读过的所有教科书和文档都表明我应该构建我的代码:

class Character():
    'Common base class for all characters'
    def __init__(self, attack, defence, strength):
        self.attack = attack
        self.defence = defence
        self.strength = strength

    def setAttack(self, attack):
        self.attack = attack

    def setDefence(self, defence):
        self.defence = defence

    def setStrength(self, strength):
        self.strength = strength


class Enemy(Character):
    'Enemy Class'
    def __init__(self, attack,defence,strength):
        Character.__init__(self, attack, defence, strength)
        self.attack = attack
        self.defence = defence
        self.strength = strength
        self.setAttack(random.randint(5,20))
        self.setDefence(random.randint(5,20))
        self.setStrength(random.randint(5,20))

哪个好,但是这意味着我必须通过设置攻击,防御和力量来声明进入Child类的内容以创建敌人

enemy1 = Enemy(10,10,10)

我想知道我的方法是否不正确,以及我是否遗漏了类如何工作的问题。我读过的所有文档似乎都指出了我的代码错误,但替代方案似乎否定了对Child Class的需求。因此我首次在stackoverflow上发帖。

1 个答案:

答案 0 :(得分:2)

调用超级 init 方法是一种很好的做法,所以我建议:

class Character():
    'Common base class for all characters'
    def __init__(self, attack, defence, strength):
        self.attack = attack
        self.defence = defence
        self.strength = strength


class Enemy(Character):
    'Enemy Class'
    def __init__(self):
        Character.__init__(self, attack=random.randint(5,20),
            defence=random.randint(5,20), strength=random.randint(5,20))

不需要制定者。