finding name of instances created

André Roberge andre.roberge at gmail.com
Fri Jan 21 20:01:00 EST 2005


Craig Ringer wrote:
> On Fri, 2005-01-21 at 16:13 -0800, André wrote:
> 
>>Short version of what I am looking for:
>>
>>Given a class "public_class" which is instantiated a few times e.g.
>>
>>a = public_class()
>>b = public_class()
>>c = public_class()
>>
>>I would like to find out the name of the instances so that I could
>>create a list of them e.g.
>>['a', 'b', 'c']
[snip]
> 
> 
> I'm not really able to grasp what you're trying to do (but others
> might). It wouldn't hurt if you could post a description of what you're
> actually trying to achieve - /why/ you want this - as that can often be
> very helpful both in understanding what you're thinking and in
> suggesting a suitable approach or alternative.
> 

Ok, here it goes... I am designing a "learning environment" for Python.
(See rur-ple.sourceforge.org for details of a *very early, still buggy* 
relase).  I have a "world" in which a
"robot" can accomplish four built-in instructions: move(), turn_left(), 
pick_beeper(), put_beeper().
turn_left() corresponds to a 90 degree left turn.  One can define a 
function to simulate a 90 degree right turn as follows:

def turn_right():
     turn_left()
     turn_left()
     turn_left()

and call it as a built-in instruction thereafter.

By giving more and more complicated tasks for the robot to accomplish,
one can learn various programming concepts using python syntax:
def (as above), while, if, else, elif, ......

I have all of that working well so far (not on sourceforge yet).
Next, I want to introduce
the concept of classes and objects, again using python's syntax.

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()

I have tried various things at the interpreter, found that
to a class 'a', I could see the instance 'b' created in
locals():
'a': <class '__main__.a'>, 'b': <__main__.a object at 0x011515D0>
which tells me that there must be a way to catch b's name as it is
created, and do what I want to do.

Does this clarify what I am trying to do and why?

André




More information about the Python-list mailing list