finding name of instances created
Steven Bethard
steven.bethard at gmail.com
Fri Jan 21 22:09:38 EST 2005
André Roberge wrote:
> Behind the scene, I have something like:
> robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
> and have mapped move() to correspond to
> robot_dict['robot'].move()
> (which does lots of stuff behind the scene.)
>
> I have tested robot_dict[] with more than one robot (each with
> its own unique name) and am now at the point where I would like
> to have the ability to interpret something like:
>
> alex = CreateRobot()
> anna = CreateRobot()
>
> alex.move()
> anna.move()
>
> etc. Since I want the user to learn Python's syntax, I don't
> want to require him/her to write
> alex = CreateRobot(name = 'alex')
> to then be able to do
> alex.move()
If you have access to the user module's text, something like this might
be a nicer solution:
py> class Robot(object):
... def __init__(self):
... self.name = None
... def move(self):
... print "robot %r moved" % self.name
...
py> class RobotDict(dict):
... def __setitem__(self, name, value):
... if isinstance(value, Robot):
... value.name = name
... super(RobotDict, self).__setitem__(name, value)
...
py> user_code = """\
... alex = Robot()
... anna = Robot()
... alex.move()
... anna.move()"""
py> robot_dict = RobotDict()
py> robot_dict['Robot'] = Robot
py> exec user_code in robot_dict
robot 'alex' moved
robot 'anna' moved
Note that I provide a specialized dict in which to exec the user code --
this allows me to override __setitem__ to add the appropriate attribute
to the Robot as necessary.
Steve
More information about the Python-list
mailing list