开发者

Python Chain getattr as a string

开发者 https://www.devze.com 2023-01-08 01:46 出处:网络
import amara def chain_attribute_call(obj, attlist): \"\"\" Allows to execute chain attribute calls \"\"\"
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.


you could also use:

from operator import attrgetter
attrgetter('x.y.z')(doc)


Just copying from Useful code which uses reduce() in Python:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号