python - Setter dict 就像对象中的属性一样

标签 python

我尝试像对象中的属性一样使用字典。这是一个玩具类。

class A(object):
    def __init__(self):
        self._b = {}

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, value):
        self._b['some_key'] = value

@property 工作正常,但 setter 给出此错误:

TypeError: 'dict' object is not callable

我猜问题是新对象无法访问字典。我必须创建一个新的 dict 类来允许我做到这一点?

最佳答案

您的错误可能是您在某个地方显式调用了函数b。例如

x = A();
x.b();

@property不允许正常调用函数,而将b完全视为普通实例变量,显然是不可调用的。

关于python - Setter dict 就像对象中的属性一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42580980/

相关文章:

javascript - 每当我通过 ajax 调用它时,Django Rest 框架都会用 AnonymousUser 替换我当前经过身份验证的用户?

python - 将 pandas 数据框中的列值乘以列标题

python - 如何记录拉伸(stretch) FITS 图像并更改其对比度?

Python selenium webdriver - 驱动程序突然出现 "dies"并且无法退出,获取 current_url,打开页面

python - Kivy的几个属性的继承

python - 使用Python子进程执行shell命令

python - Django:如何使用 Ajax 点赞对象

python - Pandas 数据帧 : convert Date format between two totally different formats

python - 如何让Qtextedit变成文本且不可选择?

python - if comment.name == user 无法正常工作