[Tutor] class awareness of variable name

Alan Gauld alan.gauld at btinternet.com
Mon Sep 17 19:54:43 CEST 2007


"Eric Abrahamsen" <eric at abrahamsen.com> wrote

> to do it. I was thinking of cleaner ways of giving an instance a
> 'name' attribute than
>
> instance_name = Class('instance_name')

The thing is that you shouldn't even try!
The object can have a name and that name will be constant
regardless of which variable is used to reference it. Don't try
to associate variables with object identifiers, they are
fundamentally different things.

If you want to identify an object by its name inside a program
the best way to do that is via a dictionary:

objects = {}
objects['foo'] = MyObject('foo')

Now, no matter which other variables reference it you
can always go to the dictionary and pull out a reference
using the object's name. And if you want to avoid typing errors use a 
temp:

temp = MyObject('bar')
objects[temp.name] = temp

And if thats too much work use a factory function:

def addObject(name):
    objects[name] = MyObject(name)



> I know  there are problems with multiple bindings,

Don't think of them as *problems*, just a different way of
working :-)

If you go with the flow rather than trying to make the flow
go the way you want life is easier.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list