使对象的属性可迭代

jos*_*inm 2 python iteration google-app-engine

我收到一个包含多个属性的列表,如下所示:

results = q.fetch(5)
for p in results:
    print "%s %s, %d inches tall" % (p.first_name, p.last_name, p.height
Run Code Online (Sandbox Code Playgroud)

是否有可能迭代这些属性,所以我可以做类似的事情for x in p.我想检查每一个的值,但我不想创建一个巨大的IF语句块.

mar*_*cog 6

我警告不要这样做.很少有例外情况需要保证,但几乎所有时候最好避免使用这种黑客解决方案.但是,如果您愿意,可以使用vars()获取属性字典并迭代它.正如@Nick在下面指出的那样,App Engine使用属性而不是值来定义其成员,因此您必须使用它getattr()来获取它们的值.

results = q.fetch(5)
for p in results:
    for attribute in vars(p).keys()
        print '%s = %s' % (attribute, str(getattr(p, attribute)))
Run Code Online (Sandbox Code Playgroud)

演示了什么vars():

>>> class A:
...     def __init__(self, a, b):
...         self.a = a
...         self.b = b
... 
>>> a = A(1, 2)
>>> vars(a)
{'a': 1, 'b': 2}
>>> for attribute in vars(a).keys():
...     print '%s = %s' % (attribute, str(getattr(a, attribute)))
... 
a = 1
b = 2
Run Code Online (Sandbox Code Playgroud)