python - 为什么自定义 Python 类实例的 `__dict__` 属性是类的描述符,而不是实例的实际属性?

标签 python python-3.x python-descriptors

来自 https://stackoverflow.com/a/44880260/156458

Note that the __dict__ attribute of custom Python class instances is a descriptor; the instance itself doesn't have the attribute, it is the class that provides it (so type(instance).__dict__['__dict__'].__get__(instance) is returned). object.__dict__ may exist, but object.__dict__['__dict__'] does not.

为什么自定义 Python 类实例的 __dict__ 属性是类的描述符,而不是实例的实际属性?

最佳答案

很容易说 __dict__ 必须是描述符,因为将其实现为 __dict__ 条目需要您在之前找到 __dict__您可以找到 __dict__,但是 Python 在查找其他属性时已经绕过正常的属性查找来查找 __dict__,因此这并不像最初听起来那么引人注目。如果描述符被每个 __dict__ 中的 '__dict__' 键替换,__dict__ 仍然可以找到。

在每个 __dict__ 中没有 '__dict__' 的键可以节省一些空间,但这不是主要原因。不必设置 '__dict__' 键也可以节省时间,不创建循环引用可以节省时间和空间,这些好处都非常好,但它们可能仍然比接下来的事情。

要求 __dict__ 成为描述符的重要事情是处理重新分配或删除对象的 __dict__ 的尝试。如果 __dict__ 的属性查找通过 __dict__ 键进行,则重新分配 someobj.__dict__ 将重新分配 dict 键而不更改 Python 实际查找的字典找到 someobj 的属性。 __dict__ 需要是一个描述符,以便它与 Python 查找对象字典的实际 C 级结构槽保持同步。

关于python - 为什么自定义 Python 类实例的 `__dict__` 属性是类的描述符,而不是实例的实际属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46575934/

相关文章:

python - 如何输入提示 python magic __get__ 方法

Python反向跨步切片

javascript - 在 Python 中模仿 JavaScript 数组

python - Python 3.6+ 中是否有格式化的字节字符串文字?

python - 以声明方式设置类 __name__

python - 向 Python 子类添加描述符

python - 当另一个数据库插入一条记录时如何更新一个数据库?

python - 如何根据 csr 矩阵交叉检查 python 字典列表

python - 使用 BeautifulSoup4 和 Python 3.3 解析错误

python - 理解 python id() 的唯一性