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()
Uh. Try explaining this to newbies... ;) On a second thought, the idea is quite usable considering some differences: class Robot(object): # as above class Robots(dict): def new(self, name): new_robot = Robot(name) self[name] = new_robot return new_robot def __getattr__(self, name): if name in self: return self[name] raise AttributeError robots = Robots() robots.new('Bert') robots.new('Ernie') robots.Bert.sayhi() robots["Bert"].sayhi() for robot in robots: robot.sayhi() ... etc ... This doesn't include ugly globals() and exec "tricks". Georg -- http://mail.python.org/mailman/listinfo/python-list