finding name of instances created

Nick Coghlan ncoghlan at iinet.net.au
Sun Jan 23 02:18:53 EST 2005


André wrote:
> So, students will be able to write:
> pete = CreateRobot(2, 3)
> pete.move()
> 
> learning about objects and methods.
> 
> As for things like
> for robot in robots:
> do stuff
> 
> that will be for my use only: drawing robots on the screen, updating
> the 'world' when robots pick stuff up, etc.  My intention is that the
> students will use the EXACT python syntax, so that they don't know that
> *I* have given a *name* to their robot(s) behind the scene.
> I have to cut this short; I hope it clarifies my intentions.

My (and, if I understand him correctly, Jeremy's) concern would be that error 
messages like "Robot 'pete' has hit a wall!" would give students the impression 
that the robots automatically know their name as a result of the assignment. In 
standard Python, that simply isn't true.

If, instead, CreateRobot looked something like:

def CreateRobot(street, avenue, name=None):
   if name is None:
     name = "Robot" + Robot.getNextNumber()
   return Robot(street, avenue, name)


Then, using a simple assignment:

pete = CreateRobot(2, 3)
pete.move()

Would give an error like:

"Robot1 has hit a wall"

This could then be used to point out that objects named using assignment don't 
know about the names they have been given, and need to be told:

pete = CreateRobot(2, 3, "Pete")
pete.move()

"Pete has hit a wall"

Instead of misleading the students ("objects know what names they have been 
given"), you have taught them a powerful truth - objects and the names you give 
them via assignment are entirely independent.

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

Internally, idioms like "for robot in robots" should be entirely unaffected - 
the registration of the robot instance with the global list of robots can be 
handled by the robot initialisation method.

Regards,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list