self naming class?

Chris Barker chrishbarker at home.net
Thu Oct 18 19:22:27 CEST 2001


Luigi Ballabio wrote:
> At 10:05 PM 10/18/01 +1000, Serge Rey wrote:
> >i'm trying to create a class that assigns a name attribute in such a way
> >that the name is set equal to the name of the instance. for example:
> >
> >test = MyClass()
> >
> >so that test.name == "test"
> I see a phylosophical problem with the above, which is, "test" is not the
> name of your instance but rather the name of a reference to such instance.

Luigi is right, and while I'm sure that someone on this group could find
a way to do it, you probably don't want to. What you need to do is step
back and ask yourself why you want to so this at all. In general, having
a link between the data and actual variable names can make it a little
easier to think about the code, but takes away a lot of flexibility, and
is ripe for the kind of problems that Luigi has pointed out,
particularly in Python.

When I want a bunch of instances to have useful names that I can refer
to them by, I usually put them in a dictionary:

d = {}
dict["test"] = MyClass()
dict["test2"] = MyClass()

or if you want the instance to have a name atribute:

thisname = "test"
dict[thisname] = MyClass(name = thisname)

Note, however, that I probably wouldn't do this (or what you have
proposed) at all. If the object has a name attribute, than you don't
want a duplication of data, there is too much of a chance of it getting
mixed up. You might do:

thisname = "test"
instance = MyClass(name = thisname)

dict[instance.name] = instance

that way you are guaranteed that the names match.

A good general rule is that if it is hard to do something in Python, you
are probably trying to solve a problem in a non "Pythonic" way, and you
should step back and find a more natural way to do it.


-Chris









-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list