我有一个带有多个属性和方法的 python 对象。 我想遍历对象的属性。
class my_python_obj(object):
attr1='a'
attr2='b'
attr3='c'
def method1(self, etc, etc):
#Statements
我想生成一个字典,其中包含对象的所有属性及其当前值,但我想以一种动态的方式来完成(因此,如果以后我添加了另一个属性,就不必记得更新我的函数了)。
在 php 中,变量可以用作键,但在 python 中,对象是不可手写的,如果我使用点符号,就会用我的变量名创建一个新属性,这不是我的本意。
为了更清楚地说明问题
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
更新: 我指的属性只是该对象的变量,而不是方法。
假设您有一个类,如
>>> class Cls(object):
... foo = 1
... bar = 'hello'
... def func(self):
... return 'call me'
...
>>> obj = Cls()
在对象上调用 dir
会返回该对象的所有属性,包括 python 特殊属性。尽管某些对象属性是可以调用的,例如方法。
>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']
您可以使用列表理解过滤掉特殊方法。
>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']
或者使用 map/filters。
>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']
如果要过滤方法,可以使用内置的 callable
作为检查。
>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))]
['bar', 'foo']
您还可以使用以下方法检查类与其实例对象之间的差异。
>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])
python 中的对象将其属性(包括函数)存储在一个名为 __dict__
的 dict 中。您可以(但一般不应该)用它来直接访问属性。如果只需要一个列表,也可以调用 dir(obj)
,它会返回一个包含所有属性名的可迭代数,然后将其传递给 getattr
。
然而,需要对变量名做任何处理通常都是糟糕的设计。为什么不将它们保存在一个集合中呢?
class Foo(object):
def __init__(self, **values):
self.special_values = values
然后,您就可以使用 "for key in obj.special_values:`" 来遍历键值。