gpt4 book ai didi

python - __dict__ 终极基类的属性,Python 中的对象

转载 作者:行者123 更新时间:2023-12-03 23:05:56 26 4
gpt4 key购买 nike

以下代码按排序顺序列出了名为“A”的类的属性:-

>>> class A():
def __init__(self, i):
self.at = i

>>> sorted(vars(A))
['__dict__', '__doc__', '__init__', '__module__', '__weakref__']
现在,打印 key 的值, '__dict__'结果如下:-
>>> vars(A)['__dict__']                 #Value of '__dict__'
<attribute '__dict__' of 'A' objects>
根据文档, vars([object])

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.



我不明白的是 '__dict__'列表中的属性 相同属性 vars() 使用返回 A 的属性或者是 不同的属性 它有另一个目标,例如按照 '__dict__' 的值(根据我的说法)实现 A 对象的命名空间。持有。

编辑:-
问题的第一部分与此非常相关 other question (也由@eliotness 提到)但这是第二部分(如下所述),我找不到任何答案或相关问题,因此更改了问题的标题。

让我们考虑另一个在 Python 中生成最终基类属性列表的代码, object :-
>>> sorted(vars(object))
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', ...., '__str__', '__subclasshook__']
>>> hasattr(object, '__dict__')
True
>>> sorted(getattr(object, '__dict__')) == sorted(vars(object))
True
来自文档的另一个引文关于 object.__dict__

A dictionary or other mapping object used to store an object’s (writable) attributes.



这一次, '__dict__'没有出现在 object 的列表中.那么,是不是 __dict__object 的情况下,attribute 是只读属性或任何其他原因?
另外,是否有可能以任何方式获取 Python 中的只读属性列表?

最佳答案

linked answer 已经回答了您问题的第一部分: __dict__实例存储为 descriptor在类里面。这是A.__dict__['__dict__'] . A.__dict__另一方面存储 A 的所有属性。 class - 它本身是 type 的一个实例.所以实际上是type.__dict__['__dict__']提供这些变量:

>>> type.__dict__['__dict__']
<attribute '__dict__' of 'type' objects>
>>> A.__dict__ == type.__dict__['__dict__'].__get__(A)
True
您没有看到 __dict__ 的原因 object 上的属性是因为它没有。这意味着您不能在 object 上设置实例变量实例:
>>> o = object()
>>> o.x = 1

AttributeError: 'object' object has no attribute 'x'
通过定义 __slots__ 可以为自定义类实现类似的行为。 :
>>> class B:
... __slots__ = ()
...
>>> vars(B)
mappingproxy({'__module__': '__main__', '__slots__': (), '__doc__': None})
>>>
>>> b = B()
>>> b.x = 1

AttributeError: 'B' object has no attribute 'x'

关于python - __dict__ 终极基类的属性,Python 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62722528/

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