我有一个班级比赛:
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'
与其他类似方法相同。
您已为实例指定了一个名为的属性result
:
self.result = result
现在将掩盖该方法。如果不想屏蔽该方法,则不能使用与该方法相同的名称。重命名属性或方法。
您可以使用该名称_result
作为示例:
def result(self):
# somehow find the game result
self._result = result
return self._result
self
只是对相同对象的另一个m
引用。在上设置或找到的属性与在上找到的属性self
相同m
,因为它们是同一对象。之间m.result
和self.result
此处没有区别。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句