variable variables?

Ben Wolfson rumjuggler at cryptarchy.org
Wed Aug 9 20:49:27 EDT 2000


On Thu, 10 Aug 2000 00:38:20 GMT, "Matthew R. MacIntyre"
<matt at matty.dyndns.org> wrote:

>
>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?

In the case where you're only dealing with a class, it's very doable:

class Test:
	def __init__(self, dict):
		for k, v in dict.items():
			self.__dict__[k] = v

But that obviously doesn't solve the general case.

-- 
Barnabas T. Rumjuggler's page of dumbth: members.home.net/rumjuggler

First we cook, then we chill.
 -- Jordan Fox



More information about the Python-list mailing list