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

Kevin Cazabon kevin_cazabon at hotmail.nospamplease!.com
Sun Mar 11 02:33:41 EST 2001


You could "assign" it a name when you create the instance:

FooBar = Foo()
FooBar.name = "FooBar"

This would let you trace it later... not elegant though.  You could also
make it an initialization parameter.

FooBar = Foo(name="FooBar")

Just trying to help... not elegantly though.


Kevin




"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)










More information about the Python-list mailing list