Communicating between objects in Python

2019-07-04 14:12发布

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

4条回答
Anthone
2楼-- · 2019-07-04 14:17

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()
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-04 14:33

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.

class exampleClass(object):

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

class exampleClass2(exampleClass):
    def callDefDoSomething(self):
        exampleClassInstance = exampleClass()
        print exampleClassInstance.doSomething(5)

exampleClass2Instance = exampleClass2()

exampleClass2Instance.callDefDoSomething()

If you want to call methods on classes you should try classmethods. Check the documentation on classes in the python tutorial.

查看更多
再贱就再见
4楼-- · 2019-07-04 14:38

You can use this:

class exampleClass(object):
    def doSomething(self,number):
        return number + 1

class exampleClass2(exampleClass):
    def callDefDoSomething(self):
        print super(exampleClass2,self).doSomething(5)

example = exampleClass2()
example.callDefDoSomething()
查看更多
贼婆χ
5楼-- · 2019-07-04 14:41

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`.

查看更多
登录 后发表回答