python - 使 __dict__ 成为一个属性

标签 python datamodel bunch

为什么这有效:

class Bunch(dict):

    def __init__(self, *args, **kwargs):
        super(Bunch, self).__init__(*args, **kwargs)
        self.__dict__ = self

b = Bunch()
b["a"] = 1
print(b.a)

尽管有循环引用:

import sys
print(sys.getrefcount(b))
# ref count is 3 when normally it is 2

但不是这个:

class Bunch(dict):

    @property
    def __dict__(self):
        return self

b = Bunch()
b["a"] = 1
b.a

# raises AttributeError

虽然从外观上看,__dict__ 是一个属性,但在幕后实现了一些特殊行为,绕过了属性创建的描述符逻辑。

最佳答案

默认的__dict__属性基本上已经一个属性。 (它实际上并不是一个属性,但它是通过描述符协议(protocol)实现的,就像属性一样。)

当您设置 self.__dict__ = self 时,它将通过 __dict__ 描述符的 __set__ 方法并替换用于实例属性的字典。

然而,Python在执行属性操作时并不使用__dict__描述符来查找实例字典;它使用不同的内部机制。因此,创建您自己的 __dict__ 描述符不会影响第二个示例中 b.a 的属性查找机制。

关于python - 使 __dict__ 成为一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45309825/

相关文章:

Python - 无法导入 Seaborn

python - 在 Linux 中显示磁盘记录的 GUI 编程

curl - 如何创建 ElasticSearch 类型并使其可在索引内搜索

symfony - 使用 Symfony 时如何处理连接表中的其他列?

python - Python的Bunch可以递归使用吗?

python - 在 Bunch 类型对象中设置和获取属性

python - 如何使用 BeautifulSoup 处理特定标签中的不同格式

python - suds 库中的自定义身份验证 (Python)

Excel VBA 将表添加到数据透视表数据模型