Python 3类继承带参数

Met*_*cry 6 parameters inheritance attributes subclass python-3.x

所以我有一个类,字符()和子类,npc(字符).它们看起来像这样:

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

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
Run Code Online (Sandbox Code Playgroud)

然而,当我从'Npc'中调用'Character'中应该存在(或者我认为)的属性时,比如'name'或'desc'或'attr',我得到一个"不存在/未定义"的错误.我只是不做继承吗?这里发生了什么?我混淆了属性和参数吗?

小智 11

你的类角色的构造函数是:

class character():
    def __init__(self, name, desc):
Run Code Online (Sandbox Code Playgroud)

所以你必须准确的名字和desc当你使npc herited.因为我个人更喜欢超级,这将是:

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
Run Code Online (Sandbox Code Playgroud)