简体   繁体   中英

Python Chain getattr as a string

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM