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

Steve Purcell stephen_purcell at yahoo.com
Thu Mar 8 03:39:17 EST 2001


Tim CHURCHES wrote:
> ...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"?


Hmmm. There's no way to do this without telling Foo its name explicitly.
If there are two names for a Foo instance, what would you like 'whoami' to
print?

>>> foobar = Foo()
>>> another_name_for_that_foo = foobar
>>> foobar
<__main__.Foo instance at 807e0b8>
>>> another_name_for_that_foo 
<__main__.Foo instance at 807e0b8>
>>> 


See the problem?

-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list