gpt4 book ai didi

python - 让所有属性出现在 python 的 `__dict__` 方法上

转载 作者:太空狗 更新时间:2023-10-30 02:28:01 24 4
gpt4 key购买 nike

请考虑以下 python 示例:

In [3]: class test(object):
...: attribute='3'
...: def __init__(self):
...: self.other='4'
...:

In [4]: b=test()

In [5]: b.attribute
Out[5]: '3'

In [6]: b.__dict__
Out[6]: {'other': '4'}

为什么 __dict__ 只显示 "other" 属性而不显示 "atribute"

我如何获得包含所有类的属性和值的字典?也就是说,我如何获得它?

{'other': '4', 'attribute': '3'}

我的意思是使用 __dict__ 或其他一些简单的方法。

PS:与this question相关, 但不能完全从那里得到命令。

PS2:我不是在寻找test.__dict__b.__class__.__dict__,我在寻找可以用作

In [3]: class test(object):
...: attribute='3'
...: def __init__(self):
...: self.other='4'
...: def _print_atr(self):
...: # This should print exactly {'other': '4', 'attribute': '3'}
...: print(self.__all_atr__)

In [4]: b=test()

In [5]: b.attribute
Out[5]: '3'

In [6]: b.__dict__
Out[6]: {'other': '4'}

干杯

最佳答案

attribute 不是实例属性而是类属性(可以在mappingproxy test.__dict__ 中看到)。

如果从实例中更新 attribute 的值,则可以在实例 __dict__ 中获取 attribute:

>>> b = test()
>>> b.__dict__
{'other': '4'}
>>> b.attribute
'3'
>>> b.attribute = 5
>>> b.__dict__
{'attribute': 5, 'other': '4'}

或者保留原来的值

>>> b.attribute  = b.__class__.attribute # may not be necessary

或者您可以更改类的定义并将 attribute 移动到其中一个类方法中,然后通过 self 将其绑定(bind)到实例。

关于python - 让所有属性出现在 python 的 `__dict__` 方法上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38362638/

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