finding name of instances created
André
andre.roberge at gmail.com
Sat Jan 22 19:04:50 EST 2005
Steven Bethard wrote:
> 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.
>
I have tried this exact example (using Python 2.3 if it makes any
difference) and what I got was:
robot None moved
robot None moved
I checked what I wrote, used cut & paste on your code, removing the
leading "junk", tried it again ... to no avail. :-(
André
More information about the Python-list
mailing list