BloonsTowerDefence
BloonsTowerDefence

Reputation: 1204

Using a variable as part of a variable name

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.

Upvotes: 0

Views: 140

Answers (3)

mgilson
mgilson

Reputation: 310167

It seems to me that if your listSubChildren method is returning strings as you imply, you can use the builtin getattr function.

>>> class foo: pass
... 
>>> a = foo()
>>> a.bar = 1
>>> getattr(a,'bar')
1
>>> getattr(a,'baz',"Oops, foo doesn't have an attrbute baz")
"Oops, foo doesn't have an attrbute baz"

Or for your example:

for name in temp_list:
    blah = getattr(object1,name)

As perhaps a final note, depending on what you're actually doing with blah, you might also want to consider operator.attrgetter. Consider the following script:

import timeit
import operator

class foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

def abc(f):
    return [getattr(f,x) for x in ('a','b','c')]

abc2 = operator.attrgetter('a','b','c')

f = foo()
print abc(f)
print abc2(f)

print timeit.timeit('abc(f)','from __main__ import abc,f')
print timeit.timeit('abc2(f)','from __main__ import abc2,f')

Both functions (abc, abc2) do nearly the same thing. abc returns the list [f.a, f.b, f.c] whereas abc2 returns a tuple much faster, Here are my results -- the first 2 lines show the output of abc and abc2 respectively and the 3rd and 4th lines show how long the operations take:

[1, 2, 3]
(1, 2, 3)
0.781795024872
0.247200965881

Note that in your example, you could use getter = operator.attrgetter(*temp_list)

Upvotes: 6

PaulMcG
PaulMcG

Reputation: 63772

Add this to the class that object1 is an instance of:

def getSubObjectAttributes(self):
    childAttrNames = "first second third".split()
    return [getattr(self, attrname, None) for attrname in childAttrNames]

Upvotes: 0

cleg
cleg

Reputation: 5022

It should look something like this:

temp_list = [] 
for property_name in needed_property_names:
    temp_list.append(getattr(object1, property_name))

So, getattr is what you need.

Upvotes: 0

Related Questions