Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python method return string rather than instancemethod

Tags:

python

oop

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!

like image 401
lamba Avatar asked Feb 10 '26 15:02

lamba


1 Answers

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()
like image 131
Rod Avatar answered Feb 12 '26 07:02

Rod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!