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

matthias.oberlaender at daimlerchrysler.com matthias.oberlaender at daimlerchrysler.com
Thu Mar 8 11:11:11 CET 2001


> "Tim CHURCHES" <TCHUR at doh.health.nsw.gov.au> wrote in message
> news:mailman.984034150.9635.python-list at python.org...
> This is probably an elementary question and the answer is probably writ
> large in multiple places in the Python documentation, but...
> 
> ...can an instance of a class determine the name of the variable to which 
it
> is assigned? For example:
> 
> ###########################
> class Foo:
>     def whoami(self):
>          return "You are a Foo() but I do not know your name"
> 
> FooBar = Foo()
> 
> print FooBar.whoami()
> ###########################
> 
> How does one define the method whoami() so that it returns "FooBar"? This
> sort of navel gazing is formally called introspection, I think (therefore I
> am)?
> 
> Tim Churches
> Sydney, Australia
> (where, due to the Coriolis effect, the Python prompt does indeed look like
> this: <<< - or maybe its because we are upside-down)

In <UPHp6.38461$1D5.1679137 at e420r-atl1.usenetserver.com> "Steve Holden" 
wrote:
> This question recurs so frequently I would appreciate knowing of any
> omprovement which could be made to FAQ entry 4.97: How can my code discover
> the name of an object?
> 
http://www.python.org/doc/FAQ.html seems to be out of data. I could not find 
4.97 on that page.
However,  the wizard finds it:
http://www.python.org/cgi-bin/faqw.py?query=4.97&querytype=simple&casefold=y
es&req=search

> This tries to address the question in a helpful manner.
> 
Yes, but here is something more constructive:

>>> def howDoYouCall(me, here):
..   # return a list of names whose value is identical to 'me' in namespace 
'here'
..   result = []
...   for (name, value) in here.items():
...     if value is me: result.append(name)
...   return result
...   
... 
>>> x = 5
>>> y = 3
>>> z = None
>>> 
>>> howDoYouCall(3, globals())
['y']
>>> howDoYouCall(5, globals())
['x']
>>> howDoYouCall(None, globals())
['__doc__', 'z']
>>> 

Does this help a bit?

--
 ____  __  _/_/ . 
( / / ( /  / / /  

=====================================================================
Matthias Oberlaender, DaimlerChrysler AG, Research Center Ulm
FT3/AB (Information Technology / Image Understanding)
Wilhelm-Runge-Str. 11,  P.O. Box 2360,  89013 Ulm, Germany
Phone: +49 731 505 2354       Fax: +49 731 505 4113
Email: matthias.oberlaender at daimlerchrysler.com
=====================================================================





More information about the Python-list mailing list