遍历python中的对象

时间:2013-07-03 22:54:00

标签: python

如何在不重复自我的情况下编写此代码?

fields = row.split('__')

if len(fields) == 1:
    foo = getattr(bundle.obj, fields[0])
elif len(fields) == 2:
    foo = getattr(getattr(bundle.obj, fields[0]), fields[1])
elif len(fields) == 3:
    foo = getattr(getattr(getattr(bundle.obj,
                            fields[0]), fields[1]), fields[2])
# etc ..

1 个答案:

答案 0 :(得分:10)

使用reduce()

foo = reduce(getattr, fields, bundle.obj)

或简单循环:

foo = bundle.obj
for field in fields:
    foo = getattr(foo, field)