如何列出一个类的所有字段(没有方法)? [英] How to list all fields of a class (and no methods)?
本文介绍了如何列出一个类的所有字段(没有方法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设o
是一个Python对象,并且我想要o
的所有字段,而没有任何方法或__stuff__
.该怎么办?
Suppose o
is a Python object, and I want all of the fields of o
, without any methods or __stuff__
. How can this be done?
我已经尝试过类似的事情:
I've tried things like:
[f for f in dir(o) if not callable(f)]
[f for f in dir(o) if not inspect.ismethod(f)]
,但是它们返回与dir(o)
相同的结果,大概是因为dir
提供了一个字符串列表.此外,即使我可以使用此命令,也会返回__class__
之类的信息.
but these return the same as dir(o)
, presumably because dir
gives a list of strings. Also, things like __class__
would be returned here, even if I get this to work.
推荐答案
You can get it via the __dict__
attribute, or the built-in vars
function, which is just a shortcut:
>>> class A(object):
... foobar = 42
... def __init__(self):
... self.foo = 'baz'
... self.bar = 3
... def method(self, arg):
... return True
...
>>> a = A()
>>> a.__dict__
{'foo': 'baz', 'bar': 3}
>>> vars(a)
{'foo': 'baz', 'bar': 3}
只有对象的属性.方法和类属性不存在.
There's only attributes of the object. Methods and class attributes aren't present.
这篇关于如何列出一个类的所有字段(没有方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文