Python 如何列出一个类的所有字段(没有方法)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21945067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:55:55  来源:igfitidea点击:

How to list all fields of a class (and no methods)?

pythonpython-2.7introspection

提问by Eric Wilson

Suppose ois a Python object, and I want all of the fields of o, without any methods or __stuff__. How can this be done?

假设o是一个 Python 对象,我想要 的所有字段o,没有任何方法或__stuff__. 如何才能做到这一点?

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)]

but these return the same as dir(o), presumably because dirgives a list of strings. Also, things like __class__would be returned here, even if I get this to work.

但这些返回与 相同dir(o),大概是因为dir给出了一个字符串列表。此外,__class__即使我让它工作,也会在这里返回类似的东西。

采纳答案by Maxime Lorant

You can get it via the __dict__attribute, or the built-in varsfunction, which is just a shortcut:

您可以通过__dict__属性或内置vars函数获取它,这只是一个快捷方式:

>>> 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.

只有对象的属性。方法和类属性不存在。

回答by Benjamin Toueg

This should work for callables:

这应该适用于可调用对象:

[f for f in dir(o) if not callable(getattr(o,f))]

You could get rid of the rest with:

您可以通过以下方式摆脱其余部分:

[f for f in dir(o) if not callable(getattr(o,f)) and not f.startswith('__')]

回答by bvidal

You could use the built-in method vars()

您可以使用内置方法 vars()

回答by BrenBarn

The basic answer is "you can't do so reliably". See this question.

基本的答案是“你不能可靠地这样做”。看到这个问题

You can get an approximation with [attr for attr in dir(obj) if attr[:2] + attr[-2:] != '____' and not callable(getattr(obj,attr))].

你可以得到一个近似值[attr for attr in dir(obj) if attr[:2] + attr[-2:] != '____' and not callable(getattr(obj,attr))]

However, you shouldn't rely on this, because:

但是,您不应该依赖于此,因为

Because dir()is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases.

因为dir()主要是为了在交互式提示下使用方便,所以它尝试提供一组有趣的名称,而不是尝试提供一组严格或一致定义的名称,并且它的详细行为可能会在不同版本中发生变化。

In other words, there is no canonical way to get a list of "all of an object's attributes" (or "all of an object's methods").

换句话说,没有规范的方法可以获取“对象的所有属性”(或“对象的所有方法”)的列表。

If you're doing some kind of dynamic programming that requires you to iterate over unknwon fields of an object, the only reliable way to do it is to implement your own way of keeping track of those fields. For instance, you could use an attribute naming convention, or a special "fields" object, or, most simply, a dictionary.

如果您正在执行某种动态编程,需要您迭代对象的未知字段,那么唯一可靠的方法是实现您自己的跟踪这些字段的方式。例如,您可以使用属性命名约定,或特殊的“字段”对象,或者最简单的字典。

回答by martineau

You can iterate through an instance's __dict__attribute and look for non-method things. For example:

您可以遍历实例的__dict__属性并查找非方法的事物。例如:

CALLABLES = types.FunctionType, types.MethodType
for key, value in A().__dict__.items():
    if not isinstance(value, CALLABLES):
        print(key)

Output:

输出:

foo
bar

You can do it in a single statement with a list comprehension:

您可以使用列表理解在单个语句中完成:

print([key for key, value in A.__dict__.items() if not isinstance(value, CALLABLES)])

Which would print ['foo', 'bar'].

哪个会打印['foo', 'bar'].