【问题标题】:Object is not callable the second time I call a class method [duplicate]我第二次调用类方法时对象不可调用[重复]
【发布时间】:2016-09-03 14:17:24
【问题描述】:

我有一个班级比赛:

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'

与其他类似方法相同。

【问题讨论】:

    标签: python


    【解决方案1】:

    你已经给你的实例一个名为result的属性:

    self.result = result
    

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

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

    def result(self):
        # somehow find the game result
        self._result = result
        return self._result
    

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

    【讨论】:

    • 哇,真快!谢谢!
    猜你喜欢
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多