Michael Tobis wrote:
I have a similar problem. Here's what I do:

.def new_robot_named(name,indict=globals()):
.   execstr = name + " = robot('" + name + "')"
.   exec(execstr,indict)

.class robot(object):
.   def __init__(self,name):
.      self.name = name

.   def sayhi(self):
.      print "Hi!  I'm %s!" % self.name

.if __name__=="__main__":
.   new_robot_named('Bert')
.   new_robot_named('Ernie')
.   Ernie.sayhi()
.   Bert.sayhi()


If you're changing the syntax from alex = CreateRobot() to new_robot_named('Alex') I don't see what you gain from using exec...

py> class robot(object):
...    def __init__(self,name):
...       self.name = name
...    def sayhi(self):
...       print "Hi!  I'm %s!" % self.name
...
py> def new_robot_named(name, indict=globals()):
...     indict[name] = robot(name)
...
py> new_robot_named('Bert')
py> new_robot_named('Ernie')
py> Ernie.sayhi()
Hi!  I'm Ernie!
py> Bert.sayhi()
Hi!  I'm Bert!
py> import new
py> temp = new.module('temp')
py> new_robot_named('Alex', temp.__dict__)
py> temp.Alex.sayhi()
Hi!  I'm Alex!

That said, I do think a 'new_robot_named' function is probably a better approach than trying to change the meaning of Python's assignment statement...

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to