[Tutor] Convert string to variable name
Tony Giunta
axg4903 at gmail.com
Thu Jan 27 03:06:12 CET 2005
On Wed, 26 Jan 2005 17:11:59 -0800 (PST), Danny Yoo
<dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> On Wed, 26 Jan 2005, Tony Giunta wrote:
>
> 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.
Yeah, that's why I was wondering if there was a better way to do it.
> So I'd recommend just using a plain old dictionary: it's not exciting, but
> it's probably the right thing to do.
Thanks. I thought I might have to resort to this. =)
> 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
Ahh. Thanks for the links, I shall check them out.
> 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!
Thanks again Danny. This is exactly what I was looking for.
tony
More information about the Tutor
mailing list