【问题标题】:Error "'str' object is not callable" when using property setter使用属性设置器时出现错误“'str' object is not callable”
【发布时间】:2018-12-05 11:23:03
【问题描述】:

我正在尝试使用如下的属性设置器。我在这里按照示例进行操作: How does the @property decorator work?

class Contact:
    def __init__(self):
        self._funds = 0.00

    @property
    def funds(self):
        return self._funds

    @funds.setter
    def funds(self, value):
        self._funds = value

getter 工作正常

>>> contact = Contact()
>>> contact.funds
0.0

但我缺少关于二传手的一些东西:

>>> contact.funds(1000.21)

Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1315, in __run
    compileflags, 1) in test.globs
  File "<doctest __main__.Contact[2]>", line 1, in <module>
    contact.funds(1000.21)
TypeError: 'str' object is not callable

我在这里做错了什么?

【问题讨论】:

  • contact.funds = 1000.21

标签: python python-decorators


【解决方案1】:

只需使用contact.funds = 1000.21 语法。它将使用@funds.setter 设置它。

我无法重现您的'str' object is not callable 错误,而是收到'float' object is not callable 错误。有关如何运行的更多详细信息将有助于诊断。无论如何,原因是contact.funds 将返回contact._funds 的值,它不是可调用对象,因此会出现错误。

【讨论】:

  • 这并没有回答他关于他在这里做错了什么的问题
  • @APorter1031 虽然我认为这个问题的答案是不言自明的,但我已经更新了我的答案以反映这一点。
  • @MoxieBall,对不起,我正在简化代码以将其归结为最简单的形式。我在返回之前修改了字符串。我将其取出并将其更改为 int 但从未更新错误消息。感谢您提供答案。
【解决方案2】:

@MoxieBall@pavan 已经展示了语法。我会深入一点来帮助解释发生了什么。

@property 装饰器精确存在,因此您可以通过方便的 x = object.fieldobject.field = value 语法获取和设置对象字段。所以@MarkIrvine,您已经正确地完成了所有操作,使您的contact.funds() getter 变为contact.funds 和您的contact.funds(value) setter 变为contact.funds = value

混淆在于@property 装饰器重新定义了联系人对象中的符号。换句话说,contact.funds Descriptor object。将 @funds.setter 装饰器应用到 def funds(self, value): 后,funds 函数将不再存在,因为您定义它。所以contact.funds(value) 首先返回contact.funds 属性,然后尝试调用它,就好像它是一个函数一样。

希望对您有所帮助。 =)

【讨论】:

  • 感谢您的额外说明。
猜你喜欢
  • 2019-10-08
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 2013-05-28
  • 2021-02-03
相关资源
最近更新 更多