使用 属性 setter 时出现错误“'str' 对象不可调用”
Error "'str' object is not callable" when using property setter
我正在尝试使用 属性 setter,如下所示。我在这里遵循示例:
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
但我遗漏了有关 setter 的一些信息:
>>> 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
语法。它将使用 @funds.setter
.
进行设置
我无法重现您的 'str' object is not callable
错误,而是收到 'float' object is not callable
错误。有关它如何 运行 的更多详细信息将有助于诊断。无论如何,原因是 contact.funds
会返回 contact._funds
的值,它不是可调用对象,因此会出现错误。
@MoxieBall and @pavan 已经显示了语法。我将深入探讨一下,以帮助解释发生了什么。
@property
装饰器恰好存在,因此您可以通过方便的 x = object.field
和 object.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)
首先 returns contact.funds
属性,然后尝试调用它,就好像它是一个函数一样。
希望对您有所帮助。 =)
我正在尝试使用 属性 setter,如下所示。我在这里遵循示例: 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
但我遗漏了有关 setter 的一些信息:
>>> 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
语法。它将使用 @funds.setter
.
我无法重现您的 'str' object is not callable
错误,而是收到 'float' object is not callable
错误。有关它如何 运行 的更多详细信息将有助于诊断。无论如何,原因是 contact.funds
会返回 contact._funds
的值,它不是可调用对象,因此会出现错误。
@MoxieBall and @pavan 已经显示了语法。我将深入探讨一下,以帮助解释发生了什么。
@property
装饰器恰好存在,因此您可以通过方便的 x = object.field
和 object.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)
首先 returns contact.funds
属性,然后尝试调用它,就好像它是一个函数一样。
希望对您有所帮助。 =)