finding name of instances created

Steven Bethard steven.bethard at gmail.com
Sun Jan 23 22:37:08 CET 2005


Nick Coghlan wrote:
> It also directly addresses the question of aliasing. Think about how 
> Steven's modified dictionary would react to this code:
> 
> pete = CreateRobot(2, 3)
> dad = pete
> dad.move()
> pete.move()

If you'd like to handle these cases, but you don't want to have to 
explain aliasing right off the bat, you could try something like:

py> class Robot(object):
...     def __init__(self):
...         self.names = set()
...     def move(self):
...         if len(self.names) == 1:
...             name, = self.names
...             print "robot with name %r moved" % name
...         else:
...             print "robot with names %r moved" % sorted(self.names)
...
py> class RobotDict(dict):
...     def __setitem__(self, name, value):
...         if isinstance(value, Robot):
...             value.names.add(name)
...         super(RobotDict, self).__setitem__(name, value)
...
py> user_code = """\
... nick = Robot()
... pete = Robot()
... dad = pete
... nick.move()
... dad.move()
... pete.move()"""
py> exec user_code in RobotDict(Robot=Robot)
robot with name 'nick' moved
robot with names ['dad', 'pete'] moved
robot with names ['dad', 'pete'] moved

That is, you can just keep track of all the names of a Robot in the 
Robot object.  In the simple case, where there's only one name, you can 
display it as such.  In the more complicated case, where there's some 
aliasing, you can display the multiple aliases.  This means you don't 
have to teach about aliasing right off the bat, but if a student 
accidentally discovers it on their own, the machinery's there to explain 
it...

Steve



More information about the Python-list mailing list