Accessing an object name ?

Quinn Dunkan quinn at lira.ugcs.caltech.edu
Fri Jul 16 19:07:57 EDT 1999


On Fri, 16 Jul 1999 10:38:45 +0000, bernard <bh at cellware.de> wrote:
>
>Is there any way of mapping from an object id to an object name
>so that given the object declaration:
>
>obj1 = myClass()
>
>I can, within an instance method, access the object name 'obj1' ?
>
>bernard.

No, not really.  Actually, you can, but it's a bad idea.  You could do this:

class Foo:
	def name(self):
		g = globals()
		for key in g.keys():
			if g[key] is self:
				return key

but you really don't want to, because this will break as soon as you use
Foo from a different module.  This is because there's no real "global" in
python, just module global, so Foo won't be able to get ahold of the
right namespace.  Besides, an object can be bound to more than one name,
or to no name at all (array[0] = Foo()).

In simililar circumstances, I've done stuff like:

obj1 = myClass('obj1')

Which is cleaner anyway.

OTOH, you can get class and method names:

myClass.__name__ == 'myClass'
myClass.method.__name__ == 'method'

Binding via class or def is more special than =, I guess.




More information about the Python-list mailing list