简体   繁体   English

Python子类在构造函数中使用父变量

[英]Python subclass uses parent variables in constructor

So I'm working on a Text Based RPG and I have a class Item which looks like this: 所以我正在研究基于文本的RPG,并且有一个类Item,看起来像这样:

class Item:
    def __init__(self, name, value):
        self.name = name
        self.value = value

Next I have a weapon class which I want to have inherit from the item class, and in the weapon constructor I want it to take the "name" and "value" variables. 接下来,我要拥有一个武器类,该武器类要从item类继承,并且在武器构造函数中,我希望它采用“名称”和“值”变量。 In my head it works like this: 在我的脑海中,它的工作方式如下:

class Weapon(Item):
    def __init(self, name, value, damage):
        self.damage = damage

Which I know is wrong, but that's essentially how I think it should work. 我知道这是错误的,但是从本质上讲,这就是我认为它应该起作用的方式。 I've looked up a bunch of threads on the "super()" function, but none of the explanations seem to be doing this. 我在“ super()”函数上查找了很多线程,但是似乎没有一种解释可以做到这一点。 So is this something that's possible or should I just make the weapon class separate? 那么这有可能吗?还是我应该将武器类别分开? Also... when it does work... what would the constructor call look like? 另外...当它起作用时...构造函数调用将是什么样?

You can use it as follows inside your Weapon class: 您可以在Weapon类中按以下方式使用它:

class Weapon(Item):
    def __init__(self, name, value, damage):
        super(Weapon, self).__init__(name, value)
        self.damage = damage

And be sure to use new-style classes, ie inherit from object : 并确保使用新型类,即从object继承:

class Item(object):
    ...

Yes, calling the parent class's constructor is something that you usually need to do: 是的,通常需要执行父类的构造函数的调用:

class Weapon(Item):
    def __init__(self, name, value, damage):
        # Initialize the Item part
        Item.__init__(self, name, value)

        # Initialize the Weapon-specific part
        self.damage = damage

As for making the weapon class separate—you should read through the article on composition over inheritance . 至于将武器类别分开,您应该通读有关组成而不是继承的文章。 People have varying opinions on whether inheritance is “right” and in which situations. 人们对继承是否“正确”以及在哪种情况下有不同的看法。 Sorry that's so vague, but you haven't given that much information about your use case :-) 抱歉,这很含糊,但是您没有提供太多有关您的用例的信息:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM