[英]python method return string rather than instancemethod
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? 我如何打印“ iloveyou”而不是那样的东西?
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.method
1 and thisObj.method2
) 确保对所有方法调用都执行此操作(
self.method
1和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. 在
method2
,您可以调用函数而不是分配函数指针。
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]:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.