getattr作为字符串

getattr作为字符串

本文介绍了Python Chain getattr作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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")

为了将对象作为字符串执行链属性调用,我必须开发上面的笨拙代码段.我很好奇是否会有一个更聪明/更有效的解决方案.

In oder to execute chain attribute calls for an object as a string, I had to develop the clumsy snippet above. I am curious if there would be a more clever / efficient solution to this.

推荐答案

只需从:

from functools import reduce
reduce(getattr, "X.Y.Z".split('.'), doc)

这篇关于Python Chain getattr作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 05:59