类继承,使用子类设置父类

2024-07-02 10:11:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力学习更多关于Python类的知识,并且正在编写一个程序来帮助解决这个问题。我将父类和子类定义如下:

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

我的观点是我可以用不同的随机值复制敌方类来创建不同类型的敌人。i、 创建一个与上面相同但随机值不同的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))

这很好,但这意味着我必须通过设置攻击、防御和力量来宣布进入儿童课程的内容,以便创建敌人

enemy1 = Enemy(10,10,10)

我想知道我的方法是否不正确,是否遗漏了一些关于类如何工作的内容。我读过的所有文档似乎都指出我的代码有错,但另一种选择似乎否定了对Child类的需要。因此我第一次在stackoverflow上发帖。你知道吗


Tags: selfinitdefrandomstrengthclassrandintcharacter
1条回答
网友
1楼 · 发布于 2024-07-02 10:11:04

调用super-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))

设置者是不必要的。你知道吗

相关问题 更多 >