Python 方法返回字符串而非实例方法

3 投票
3 回答
44577 浏览
提问于 2025-04-16 13:22

我有一个类和里面的一些方法。

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

我该怎么做才能打印出'iloveyou'而不是那个东西呢?

谢谢!

3 个回答

0
    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

method2里,你可以直接调用这个函数,而不是给它一个函数指针。

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

你在调用方法的时候忘记加括号了。没有括号的话,你实际上是在打印这个方法对象的字符串表示,而不仅仅是方法的结果。这种情况也适用于所有可以调用的对象,包括自由函数。

确保你在所有方法调用中都加上括号(比如 self.methodthisObj.method2)。

class ThisClass:

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

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

thisObj = ThisClass()
thisObj.method2()

撰写回答