简体   繁体   中英

python method return string rather than instancemethod

I got a class and a few method in it

class ThisClass:

    def method1(self):
        text1 = 'iloveyou'
        return text1

    def method2(self):
        text2 = self.method1
        print str(text2)

thisObj = ThisClass()
thisObj.method2

the result i get is something like

<bound method thisclass.method2 of <__main__.thisclass instance at 0x10042eb90>>

how do I print 'iloveyou' rather than that thing?

Thanks!

Missing the () for the method call. Without the () you are printing the string representation of the method object which is also true for all callables including free functions.

Make sure you do it for all your method calls ( self.method 1 and thisObj.method2 )

class ThisClass:

    def method1(self):
        text1 = 'iloveyou'
        return text1

    def method2(self):
        text2 = self.method1()
        print str(text2)

thisObj = ThisClass()
thisObj.method2()

in method2 , you can call the function instead of assigning a function pointer.

def method2(self):
    text2 = self.method1()
    print text2
    In [23]: %cpaste
    Pasting code; enter '--' alone on the line to stop.
    :class ThisClass:
    :
    :    def method1(self):
    :        text1 = 'iloveyou'
    :        return text1
    :
    :    def method2(self):
    :        text2 = self.method1()
    :        print str(text2)
    :--

    In [24]: thisObj = ThisClass()

    In [25]: thisObj.method2()
    iloveyou

    In [26]: 

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