简体   繁体   中英

calling a base class method in the child class python

What is going on. I have looked at other solutions on stack overflow but non seem to work from what I have seen. I have a base object with a method that changes the value of the base attribute. When I call the base function in a child class (Inheritance) I get that the child class does not have the attribute "baseAttribute"

class GameObject(object):
 #This is the base class for gameObjects
 def __init__(self):
     self.components = {}

 def addComponent(self, comp):
     self.components[0] = comp #ignore the index. Placed 0 just for illustration

class Circle(GameObject):
 #circle game object 
 def __init__(self):
     super(GameObject,self).__init__()
     #PROBLEM STATEMENT
     self.addComponent(AComponentObject())
     #or super(GameObject,self).addComponent(self,AComponentObject())
     #or GameObject.addComponent(self, AComponentObject())

EDIT: Apologies, I never originally passed in a self.

Simple - leave out the second self:

self.addComponent(AComponentObject())

You see, the above actually translates to

addComponent(self, AComponentObject())

In other words: in essence "OO" works on functions that have an implicit this / self pointer (however you name that) as argument.

You are using incorrect arguments for .addComponent() method.

# ...

class Circle(GameObject):

 def __init__(self):
     super(GameObject,self).__init__()
     # NOT A PROBLEM STATEMENT ANYMORE
     self.addComponent(AComponentObject())
     # ...

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