15

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?

1 Answer 1

26

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
Sign up to request clarification or add additional context in comments.

3 Comments

@Metalgearmaycry - Don't forget to upvote and accept answers by clicking the up arrow and green-faded tick on the left-hand side. This let's everyone know your problem has been solved :)
i know this comment is rather late, but is there a way to not call the super().__init__ method with those specific parameters but to make them a variable i can specify while creating an object of that class? something like:' x = npc("a_greeting","a_topic","a_name","a_desc") ?
@James You can make them same argument in npc.__init__(self, greet, topic, name, desc) and call super().__init__(name, desc). Or using **kwargs and pass them using key word unpack will be more flexible and easy to write.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.