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
I guess if you're right something along the lines of import inspect class A: _class_name=inspect.currentframe().f_code.co_name def __init__(self,text,_defining_class_name=_class_name): print 'text=',text,'_defining_class_name=',_defining_class_name
class B(A): pass b=B('aaa')
==>text= aaa _defining_class_name= A
could work as well, but if we only need the local name why not just insert directly.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list