简体   繁体   English

Python 3类继承带参数

[英]Python 3 class inheritance with parameters

So I have a class, character(), and a subclass, npc(character). 所以我有一个类,字符()和子类,npc(字符)。 They look like this: 它们看起来像这样:

class character():
    def __init__(self,name,desc):
        self.name = name
        self.desc = desc
        self.attr = ""    
        #large list of attributes not defined by parameters

and

class npc(character):
    def __init__(self,greetings,topics):
        self.greetings = greetings
        self.topics = topics
        character.__init__(self)
        self.pockets = []
        #more attributes specific to the npc subclass not defined by parameters

however, when I call an attribute from 'Character' that should exist (or so I think) in 'Npc', like 'name' or 'desc' or 'attr', I get a "does not exist/is undefined" error. 然而,当我从'Npc'中调用'Character'中应该存在(或者我认为)的属性时,比如'name'或'desc'或'attr',我得到一个“不存在/未定义”的错误。 Am I just not doing inheritance right? 我只是不做继承吗? What's going on here? 这里发生了什么? Am I mixing up attributes and parameters? 我混淆了属性和参数吗?

the constructor of you class character is : 你的类角色的构造函数是:

class character():
    def __init__(self, name, desc):

so you have to precise name and desc when you make npc herited. 所以你必须准确的名字和desc当你使npc herited。 As I personnaly prefer super this would be: 因为我个人更喜欢超级,这将是:

class npc(character):
    def __init__(self,greetings,topics):
        super().__init__("a_name", "a_desc")
        self.greetings = greetings
        self.topics = topics
        self.pockets = []
        #more attributes specific to the npc subclass not defined by parameters

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

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