variable variables?

Matthew R. MacIntyre matt at matty.dyndns.org
Wed Aug 9 20:38:20 EDT 2000


Hello all,

Does python support "variable variables"?  I've been trying something like
this, but to no avail:

var1 = "foo"
varname = "var1"

then i want to do something like:
{varname} = bar
print var1
=> bar

Is this do-able?

More specifically, i'm trying to set instance variables in a class using
an argument containing a dictionary in the constructor .... something like
this:

class TestClass:
	def __init__(self,dict):
           for x in dict.keys()
             self._{x} = dict[x]

	def show(self):
		print self._var1
		print self._var2

args = { 'var1' : "value1", 'var2' : "value2" }
test = TestClass(args)
test.show()

I want the test.show() to print :

value1
value2

but I'm having no such luck on the various variations of this theme that
I've been dreaming up.

Is this even possible to do?  Is it an outrageous thing to try to do?  If
so, what is a better way to do it?

Thanks,

-matt




More information about the Python-list mailing list