python方法返回字符串而不是instancemethod

2024-09-28 01:32:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一门课和一些方法

class ThisClass:

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

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

thisObj = ThisClass()
thisObj.method2

我得到的结果是

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

我怎么打印“我爱你”而不是那东西?

谢谢!


Tags: 方法selfreturndefclassprintstrtext1
3条回答
    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]: 

缺少方法调用的()。如果不使用()则打印方法对象的字符串表示形式,对于所有可调用项(包括自由函数)也是如此。

确保对所有方法调用都这样做(self.method1和thisObj.method2

class ThisClass:

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

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

thisObj = ThisClass()
thisObj.method2()

method2中,可以调用函数而不是分配函数指针。

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

相关问题 更多 >

    热门问题