[Tutor] creating variables at runtime
Kirby Urner
urnerk@qwest.net
Wed, 23 Jan 2002 20:30:12 -0800
>
>Is such a thing possible? Is it Bad and Wrong?
>
>I'm a relatively raw newcomer using Py 2.1 under windows
>
>
>David
You can do it, and many do, but I always advise that it's
safer and easier to use a dictionary to hold user-created
objects. For example:
class Thing:
def __init__(self, name):
self.myname = name
def getuser():
global userobjs
while 1:
objname = raw_input("Gimme an object (or q to quit) > ")
if not objname in ['q','Q']:
userobjs[objname] = Thing(objname)
else:
break
In the shell (or from a script):
>>> userobjs = {}
>>> getuser()
Gimme an object (or q to quit) > NARF
Gimme an object (or q to quit) > q
>>> userobjs
{'NARF': <__main__.Thing instance at 0x0113E4F0>}
>>> obj = userobjs['NARF']
>>> obj.myname
'NARF'
If you user wants to interact with the objects she or he
named, then you simply have your code look it up by name
in the userobjs dictionary, where they'll all be together.
Kirby