finding name of instances created
Georg Brandl
g.brandl-2005-01 at gmx.net
Sun Jan 23 16:03:04 EST 2005
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
More information about the Python-list
mailing list