获取Python中的所有对象属性?
有没有办法获取所有属性/方法/字段/等。 Python 中的对象?
vars()
与我想要的接近,但除非对象具有 __dict__
,否则它不起作用,而这并不总是正确的(例如,对于 list
、dict
等来说,情况并非如此)。
Is there a way to get all attributes/methods/fields/etc. of an object in Python?
vars()
is close to what I want, but it doesn't work unless an object has a __dict__
, which isn't always true (e.g. it's not true for a list
, a dict
, etc.).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用内置函数
dir()
。Use the built-in function
dir()
.我使用
__dict__
和dir()
示例:
I use
__dict__
anddir(<instance>)
Example:
您可能想要的是
dir()
。问题是类能够重写特殊的 __dir__ 方法,这会导致 dir() 返回类想要的任何内容(尽管鼓励它们返回准确的列表,这并未强制执行)。此外,一些对象可以通过重写
__getattr__
来实现动态属性,可以是RPC代理对象,或者可以是C扩展类的实例。如果您的对象是这些示例之一,则它们可能没有__dict__
或能够通过__dir__
提供全面的属性列表:许多这些对象可能有如此多的动态属性,除非您尝试访问它,否则它实际上不会知道它有什么。从短期来看,如果 dir() 还不够,您可以编写一个函数,遍历 __dict__ 来获取对象,然后遍历 __dict__ 来获取对象
obj.__class__.__mro__
中的所有类;虽然这只适用于普通的 python 对象。从长远来看,您可能必须使用鸭子类型+假设 - 如果它看起来像鸭子,请交叉手指,并希望它有.feathers
。What you probably want is
dir()
.The catch is that classes are able to override the special
__dir__
method, which causesdir()
to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding__getattr__
, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a__dict__
or be able to provide a comprehensive list of attributes via__dir__
: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.In the short run, if
dir()
isn't sufficient, you could write a function which traverses__dict__
for an object, then__dict__
for all the classes inobj.__class__.__mro__
; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has.feathers
.您可以使用 dir(your_object) 获取属性,使用 getattr(your_object, your_object_attr) 获取值
用法:
You can use
dir(your_object)
to get the attributes andgetattr(your_object, your_object_attr)
to get the valuesusage :