开发者

python method return string rather than instancemethod

开发者 https://www.devze.com 2023-02-16 00:26 出处:网络
I got a class and a few method in it class ThisClass: def method1(self): text1 = \'iloveyou\' return text1

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.metho开发者_运维技巧d2 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.method1 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]: 
0

精彩评论

暂无评论...
验证码 换一张
取 消