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

Jeremy Reed jp_reed at yahoo.com
Thu Mar 8 05:27:08 EST 2001


The easiest solution would be to give the name as a parameter at
instantiation and store it in the class as a member variable.

i.e.

class Foo:
    def whoami(self):
        print "Class: Foo   Name:",self.name
    def __init__(self, name):
        self.name = name

FooBar = Foo('FooBar')
FooBar.whoami()
#########
Class: Foo   Name: FooBar
#########
Offhand, I don't think there is a function call capable of doing what you
ask although I could be mistaken.


Tim CHURCHES wrote in message ...
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