我有一场班级比赛:
class Match(object):
def __init__(self,id):
self.id = id
def result(self):
# somehow find the game result
self.result = result
return self.result如果我将匹配对象初始化为
m = Match(1)当我调用方法结果时,我得到
m.result
Out[18]: <bound method Match.result of <football_uk.Match object at 0x000000000B0081D0>>当我用括号称呼它时,我得到
m.result()
Out[19]: u'2-3'这是正确的答案。然而,当我试图调用第二、第三、第四等时间的方法时,我得到
m.result()
Traceback (most recent call last):
File "<ipython-input-20-42f6486e36a5>", line 1, in <module>
m.result()
TypeError: 'unicode' object is not callable如果现在我调用不带括号的方法,则它有效:
m.result
Out[21]: u'2-3'其他类似的方法也是如此。
发布于 2016-09-03 14:18:26
您已经为实例提供了一个名为result的属性
self.result = result这现在掩盖了这个方法。如果不想蒙面,就不能使用与方法相同的名称。重命名属性或方法。
例如,您可以使用名称_result:
def result(self):
# somehow find the game result
self._result = result
return self._resultself只是对m引用的同一个对象的另一个引用。在self上设置或找到的属性与在m上可以找到的属性是相同的,因为它们是同一个对象。m.result和self.result在这里没有区别。
https://stackoverflow.com/questions/39307910
复制相似问题