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?
假设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 dir
gives a list of strings. Also, things like __class__
would be returned here, even if I get this to work.
但这些返回与dir(o)相同,大概是因为dir给出了一个字符串列表。此外,像__class__这样的东西会在这里返回,即使我让它工作。
5 个解决方案
#1
36
You can get it via the __dict__
attribute, or the built-in vars
function, which is just a shortcut:
您可以通过__dict__属性或内置变量函数获取它,这只是一个快捷方式:
>>> 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.
只有对象的属性。方法和类属性不存在。
#2
7
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 [:2] + attr [-2:]!='____'并且不可调用(getattr(obj,attr)],则可以使用[attr for dtr in dir(obj)得到近似值。
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 an object's attributes" (or "all 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.
如果您正在进行某种动态编程,需要您迭代对象的unknwon字段,唯一可行的方法是实现自己的方法来跟踪这些字段。例如,您可以使用属性命名约定或特殊的“字段”对象,或者最简单的使用字典。
#3
3
This should work for callables:
这适用于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('__')]
#4
3
You could use the built-in method vars()
你可以使用内置的方法vars()
#5
3
You can iterate through an instance's__dict__
attribute and look for non-method things.
For example:
您可以遍历实例的___dict__attribute并查找非方法的东西。例如:
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']。
#1
36
You can get it via the __dict__
attribute, or the built-in vars
function, which is just a shortcut:
您可以通过__dict__属性或内置变量函数获取它,这只是一个快捷方式:
>>> 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.
只有对象的属性。方法和类属性不存在。
#2
7
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 [:2] + attr [-2:]!='____'并且不可调用(getattr(obj,attr)],则可以使用[attr for dtr in dir(obj)得到近似值。
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 an object's attributes" (or "all 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.
如果您正在进行某种动态编程,需要您迭代对象的unknwon字段,唯一可行的方法是实现自己的方法来跟踪这些字段。例如,您可以使用属性命名约定或特殊的“字段”对象,或者最简单的使用字典。
#3
3
This should work for callables:
这适用于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('__')]
#4
3
You could use the built-in method vars()
你可以使用内置的方法vars()
#5
3
You can iterate through an instance's__dict__
attribute and look for non-method things.
For example:
您可以遍历实例的___dict__attribute并查找非方法的东西。例如:
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']。