I have something like this:
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def callDefDoSomething(self):
print exampleClass.doSomething(5)
exampleClass2.callDefDoSomething()
-
TypeError: unbound method callDefDoSomething() must be called
with exampleClass2 instance as first argument (got nothing instead)
I started to learn about objects in Python but i cant find solution for this :(
You need to create an instance of the class, i.e., an active object, to make things work:
Regular class methods can only be called for instances not for classes. So if you want to call callDefDoSomething you have to first instantiate exampleClass2. You also have to instantiate exampleClass inside the call to callDefDoSomething.
If you want to call methods on classes you should try classmethods. Check the documentation on classes in the python tutorial.
You can use this:
doSomething
is a method ofexampleClass
. Therefore, it has to be called for an instance of this class.In
callDefDoSomething
, you useexampleClass
, however, is not an instance of this class but the class itself. What you want to use here isself
refers to the instance of exampleClass2, for which
callDefDoSomethingsis invoked, which, due to inheritance, is an instance of
exampleClass`.