获取所有属性出现在python的`__dict__`方法上

Tom*_*Cho 5 python attributes class

请考虑以下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'}
Run Code Online (Sandbox Code Playgroud)

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

以及如何获得包含所有类的属性和值的字典?也就是说,我如何得到这个?

{'other': '4', 'attribute': '3'}
Run Code Online (Sandbox Code Playgroud)

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

PS:与这个问题有关,但不能从那里得到一个字典。

PS2:我不是在寻找test.__dict__or 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'}
Run Code Online (Sandbox Code Playgroud)

干杯

Mos*_*oye 5

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'}
Run Code Online (Sandbox Code Playgroud)

或者保持原始值

>>> b.attribute  = b.__class__.attribute # may not be necessary
Run Code Online (Sandbox Code Playgroud)

或者您可以更改类的定义并移动attribute到类方法之一并通过 将其绑定到实例self