我有一个带有几个属性和方法的python对象。我想要遍历对象属性。
class my_python_obj(object):
attr1='a'
attr2='b'
attr3='c'
def method1(self, etc, etc):
#Statements
我想生成一个包含所有对象属性及其当前值的字典,但我想以一种动态的方式来做(因此,如果后来我添加了另一个属性,我不必记得更新我的函数)。
在php中,变量可以用作键,但python中的对象是不可感知的,如果我使用点符号,它会创建一个名为我的var的新属性,这不是我的意图。
为了让事情更清楚:
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 SomeClass:
x = 1
y = 2
z = 3
def __init__(self):
self.current_idx = 0
self.items = ["x", "y", "z"]
def next(self):
if self.current_idx < len(self.items):
self.current_idx += 1
k = self.items[self.current_idx-1]
return (k, getattr(self, k))
else:
raise StopIteration
def __iter__(self):
return self
然后把它作为一个可迭代对象调用
s = SomeClass()
for k, v in s:
print k, "=", v
一般来说,在类中放入__iter__方法并遍历对象属性,或者将这个mixin类放入类中。
class IterMixin(object):
def __iter__(self):
for attr, value in self.__dict__.iteritems():
yield attr, value
你的类:
>>> class YourClass(IterMixin): pass
...
>>> yc = YourClass()
>>> yc.one = range(15)
>>> yc.two = 'test'
>>> dict(yc)
{'one': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'two': 'test'}
class SomeClass:
x = 1
y = 2
z = 3
def __init__(self):
self.current_idx = 0
self.items = ["x", "y", "z"]
def next(self):
if self.current_idx < len(self.items):
self.current_idx += 1
k = self.items[self.current_idx-1]
return (k, getattr(self, k))
else:
raise StopIteration
def __iter__(self):
return self
然后把它作为一个可迭代对象调用
s = SomeClass()
for k, v in s:
print k, "=", v