Skip to main content
 首页 » 编程设计

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

2025年05月04日17飞鱼

我有一个类和一些方法

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”而不是那个东西?

谢谢!

请您参考如下方法:

方法调用缺少 ()。如果没有 (),您将打印方法对象的字符串表示形式,这对于包括自由函数在内的所有可调用对象也是如此。

确保为所有方法调用(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()