introspection inquiry

Michael Hoffman cam.ac.uk at mh391.invalid
Sun Feb 20 10:28:11 EST 2005


Robin Becker wrote:
> self.__class__.__name__

Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.

Here's a way to do that using metaclasses and Python's magic
double-underscore attribute-mangling feature:

"""
class SelfKnowledge(type):
     def __init__(cls, name, bases, dict):
         setattr(cls, "_%s__%s" % (name, "class_name"), name)
         type.__init__(cls, name, bases, dict)

class Nietzsche(object):
     __metaclass__ = SelfKnowledge

     def __init__(self, text):
         self.spam = text
         print "In the constructor of the %s class" % self.__class_name

class Kierkegaard(Nietzsche):
     def __init__(self, text):
         print "Now in the constructor of %s" % self.__class_name
         Nietzsche.__init__(self, text)

Nietzsche("Thus Spake Zarathustra")
print

Kierkegaard("Fear and Trembling")
"""

$ python test1.py
In the constructor of the Nietzsche class

Now in the constructor of Kierkegaard
In the constructor of the Nietzsche class
-- 
Michael Hoffman



More information about the Python-list mailing list