import amara
def chain_attribute_call(obj, attlist):
"""
Allows to execute chain attribute calls
"""
splitted_attrs = attlist.split(".")
current_dom = obj
for attr in splitted_attrs:
current_dom = getattr(current_dom, attr)
return current_dom
doc = amara.parse("sample.xml")
print chain_attribute_call(doc, "X.Y.Z")
在oder中以字符串形式执行对象的链属性调用时,我不得不开发上面的笨拙片段。我很好奇是否会有更聪明/有效的解决方案。
答案 0 :(得分:21)
你也可以使用:
from operator import attrgetter
attrgetter('x.y.z')(doc)
答案 1 :(得分:9)
只需从Useful code which uses reduce()
in Python复制:
from functools import reduce
reduce(getattr, "X.Y.Z".split('.'), doc)