第二次调用类方法时,对象不可调用

ric*_*777 2 python

我上课了比赛:

class Match(object):

  def __init__(self,id):
      self.id = id

  def result(self):
      # somehow find the game result
      self.result = result
      return self.result
Run Code Online (Sandbox Code Playgroud)

如果我将匹配对象初始化为

m = Match(1)
Run Code Online (Sandbox Code Playgroud)

当我调用方法结果时,我得到了

m.result
Out[18]: <bound method Match.result of <football_uk.Match object at 0x000000000B0081D0>>
Run Code Online (Sandbox Code Playgroud)

当我用括号称它时,我得到了

m.result()
Out[19]: u'2-3'
Run Code Online (Sandbox Code Playgroud)

这是正确的答案.但是,当我尝试拨打第二,第三,第四等时间时,我得到了

m.result()
Traceback (most recent call last):

  File "<ipython-input-20-42f6486e36a5>", line 1, in <module>
m.result()

TypeError: 'unicode' object is not callable
Run Code Online (Sandbox Code Playgroud)

如果现在我调用没有括号的方法,它的工作原理:

m.result
Out[21]: u'2-3'
Run Code Online (Sandbox Code Playgroud)

与其他类似方法相同.

Mar*_*ers 6

您已为实例指定了一个名为的属性result:

self.result = result
Run Code Online (Sandbox Code Playgroud)

现在这掩盖了该方法.如果您不希望它被屏蔽,则不能使用与该方法相同的名称.重命名属性或方法.

您可以使用名称_result,例如:

def result(self):
    # somehow find the game result
    self._result = result
    return self._result
Run Code Online (Sandbox Code Playgroud)

self只是对引用的同一对象的另一个m引用.设置或找到的属性self与您可以找到的属性相同m,因为它们是同一个对象.这里m.resultself.result这里没有区别.