如何获取对象的所有字段?

Rom*_*man 0 python

免责声明:我在python中迈出了第一步,这就是为什么这个问题可能听起来有些愚蠢.

如何列出存储的所有变量self

Dan*_* D. 5

您可能希望inspect.getmembers它列出对象的成员,即使这些对象已__slots__定义为那些对象没有__dict__.

>>> import inspect
>>> class F:
...     def __init__(self):
...             self.x = 2
... 
>>> inspect.getmembers(F())
[('__doc__', None), ('__init__', <bound method F.__init__ of <__main__.F instance at 0xb7527fec>>), ('__module__', '__main__'), ('x', 2)]
>>> class F:
...     __slots__ = ('x')
...     def __init__(self):
...             self.x = 2
... 
>>> inspect.getmembers(F())
[('__doc__', None), ('__init__', <bound method F.__init__ of <__main__.F instance at 0xb72d3b0c>>), ('__module__', '__main__'), ('__slots__', 'x'), ('x', 2)]
Run Code Online (Sandbox Code Playgroud)