Who am I: can a class instance determine its own name?

Gregory Jorgensen gregj at pobox.com
Fri Mar 9 01:58:25 EST 2001


Emile van Sebille's very cool hack aside, I don't understand why you would do
this. I'm not criticizing; you've got me curious. I've never needed this in
years and years of programming. I don't think of a variable name as an attribute
of the object it refers to, because (as one poster pointed out) objects may have
no name, one name, or several names at any time, and the names referring to an
object may change during the object's lifetime through assignment, parameter
passing, etc.

Even Emile's hack has limited usefulness: it captures the name at the time the
Bar object is added to a Foo container, but consider these obvious problems:

def addbar(f, b):
f.addBar(b)

foo = Foo()
bar_a = Bar()
addbar(foo, bar_a)

bar_b = Bar()
foo.addBar(bar_b)
zzz = bar_b
del bar_b


foo.listBars() will yield ['b','bar_b'], not ['bar_a','zzz'].

You mention the "problem of composition" and give a container class example,
implying that this is a problem associated with those object-oriented designs.
Why?

Python has the "is" operator to test if two objects refer to the same thing;
that's safer than using names.

>>> b = Bar()
>>> z = b
>>> z is bar
1

I'm sure I'm not the only inquiring mind who wants to know.

Greg Jorgensen
Deschooling Society
Portland, Oregon, USA
gregj at pobox.com



More information about the Python-list mailing list