迭代对象的属性蟒 [英] Iterate over object attributes in python
问题描述
我有几个属性和方法Python对象。我想遍历对象属性。
I have a python object with several attributes and methods. I want to iterate over object attributes.
class my_python_obj(object):
attr1='a'
attr2='b'
attr3='c'
def method1(self, etc, etc):
#Statements
我要生成一个包含所有对象的属性及其当前值的字典,但我想这样做动态方式(所以如果以后我添加另一个属性我不记得我的更新功能井)。
I want to generate a dictionary containing all of the objects attributes and their current values, but I want to do it in a dynamic way (so if later I add another attribute I don't have to remember to update my function as well).
在PHP变量可以作为钥匙,但在Python对象unsuscriptable,如果我用点号这会创建一个与我的变种,这不是我的意图名称的新属性。
In php variables can be used as keys, but objects in python are unsuscriptable and if I use the dot notation for this it creates a new attribute with the name of my var, which is not my intent.
只是为了让事情更清晰:
Just to make things clearer:
def to_dict(self):
'''this is what I already have'''
d={}
d["attr1"]= self.attr1
d["attr2"]= self.attr2
d["attr3"]= self.attr3
return d
·
def to_dict(self):
'''this is what I want to do'''
d={}
for v in my_python_obj.attributes:
d[v] = self.v
return d
更新:
随着属性我的意思是只此对象的变量,而不是方法。
Update: With attributes I mean only the variables of this object, not the methods.
推荐答案
假设你有一个类,如
>>> class Cls(object):
... foo = 1
... bar = 'hello'
... def func(self):
... return 'call me'
...
>>> obj = Cls()
调用 DIR
的对象给你回该对象的所有属性,包括Python的特殊属性。虽然有些对象属性是可调用的,比如方法。
calling dir
on the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.
>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']
您可以随时使用名单COM prehension筛选出特殊的方法。
You can always filter out the special methods by using a list comprehension.
>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']
或者如果你preFER图/过滤器。
or if you prefer map/filters.
>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']
如果要过滤出的方法,您可以使用内置的可赎回
作为检查。
If you want to filter out the methods, you can use the builtin callable
as a check.
>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj,a))]
['bar', 'foo']
您还可以通过检查你的类与其父之间的区别。
You could also inspect the difference between your class and its parent using.
>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])
这篇关于迭代对象的属性蟒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!