[Tutor] Convert string to variable name
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Jan 27 02:11:59 CET 2005
On Wed, 26 Jan 2005, Tony Giunta wrote:
> This is something I've been trying to figure out for some time. Is
> there a way in Python to take a string [say something from a raw_input]
> and make that string a variable name?
Hi Tony,
Conceptually, yes: you can collect all those on-the-fly variables in a
dictionary.
> I'm sure I could accomplish something similar using a plain old
> dictionary,
Yup. *grin*
> but I was playing around with the OOP stuff and thought it might be a
> neat thing to try out.
We can use exec() to create dynamic variable names, but it's almost always
a bad idea. Dynamic variable names make it very difficult to isolate
where variables are coming from in a program. It'll also prevent us from
reliably using the excellent PyChecker program:
http://pychecker.sourceforge.net/
So I'd recommend just using a plain old dictionary: it's not exciting, but
it's probably the right thing to do.
Looking back at the code:
###
def generateInstance():
class test:
def __init__(self, title, price):
self.title = title
self.price = price
def theTitle(self, title):
return self.title
def thePrice(self, price):
return self.price
myName = raw_input("Name: ")
myTitle = raw_input("Title: ")
myPrice = raw_input("Price: ")
exec '%s = test("%s", %s)' % (myName, myTitle, myPrice)
###
In Python, we actually can avoid writing attribute getters and setters ---
the "JavaBean" interface --- because Python supports a nice feature called
"properties". See:
http://dirtsimple.org/2004/12/python-is-not-java.html
http://www.python.org/2.2.2/descrintro.html#property
The upside is that we usually don't need methods like theTitle() or
thePrice() in Python. Our revised code looks like:
###
class test:
def __init__(self, title, price):
self.title = title
self.price = price
instances = {}
def generateInstance():
myName = raw_input("Name: ")
myTitle = raw_input("Title: ")
myPrice = raw_input("Price: ")
instances[myName] = test(myTitle, myPrice)
###
If you have more questions, please feel free to ask. Best of wishes to
you!
More information about the Tutor
mailing list