简体   繁体   中英

Python 3 class inheritance with parameters

So I have a class, character(), and a subclass, npc(character). 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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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