gpt4 book ai didi

python - 错误 "' str' object is not callable"when using property setter

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:51 25 4
gpt4 key购买 nike

我正在尝试使用如下的属性 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

setter/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 的值,它不是可调用对象,因此会出现错误。

关于python - 错误 "' str' object is not callable"when using property setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com