Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicating between objects in Python

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 :(

like image 810
Ivan Vulović Avatar asked Mar 24 '23 08:03

Ivan Vulović


2 Answers

You need to create an instance of the class, i.e., an active object, to make things work:

class exampleClass(object):

    def doSomething(self,number):
        return number + 1 

class exampleClass2(exampleClass):

    def __init__(self):
        self.member1 = exampleClass()

    def callDefDoSomething(self):
        print self.member1.doSomething(5)


object2 = exampleClass2()
object2.callDefDoSomething()
like image 83
perreal Avatar answered Apr 02 '23 14:04

perreal


doSomething is a method of exampleClass. Therefore, it has to be called for an instance of this class.

In callDefDoSomething, you use

exampleClass.doSomething(5)

exampleClass, however, is not an instance of this class but the class itself. What you want to use here is

self.doSomething(5)

self refers to the instance of exampleClass2, for whichcallDefDoSomethingsis invoked, which, due to inheritance, is an instance ofexampleClass`.

like image 33
Elmar Peise Avatar answered Apr 02 '23 13:04

Elmar Peise