I have object1 which has many sub-objects in it. These sub-objects are accessed in the form object1.subobject. I have a function which returns a list of sub-objects of the original object. All I would like to do is iterate through the list and access each sub-object. Something like this:
temp_list = listSubChildren(object1) #Get list of sub-objects
for sub_object in temp_list: #Iterate through list of sub-objects
blah = object1.sub-object #This is where I need help
#Do something with blah #So that I can access and use blah
I looked at similar questions where people used dictionaries and getattr but couldn’t get either of those methods to work for this.
It seems to me that if your
listSubChildrenmethod is returning strings as you imply, you can use the builtingetattrfunction.Or for your example:
As perhaps a final note, depending on what you’re actually doing with
blah, you might also want to consideroperator.attrgetter. Consider the following script:Both functions (
abc,abc2) do nearly the same thing.abcreturns the list[f.a, f.b, f.c]whereasabc2returns a tuple much faster, Here are my results — the first 2 lines show the output ofabcandabc2respectively and the 3rd and 4th lines show how long the operations take:Note that in your example, you could use
getter = operator.attrgetter(*temp_list)