Le Friday 05 September 2008 17:29:39 mercado mercado, vous avez écrit : > In Python, is it possible for an instance method to know the name of the > class which is calling it? For example, in the sample below, I would like > for the someMethod method to print the name of the class calling it ("bar" > in the first case, "again" in the second).
Note that "self" for somemethod is just a local variable of the calling function. You cannot retrieve those local variables without playing with the call stack, and this reveal generally a bad design (except for inspection purpose). You have two common solutions here : - the simplest is to pass the instance of bar or again to the foo constructor or as parameter of someMethod, or - attach the foo instance to self in both cases and define a proper __get__ method in foo, this is far more complex and add magic to the foo class, I don't recommand this unless you understand well the descriptor protocol. > > --------------------------------------- > class foo(): > def someMethod(self): > print x > > class bar(): > def __init__(self): > f = foo() > f.someMethod() > > class again(): > def __init__(self): > f = foo() > f.someMethod() > > bar() > again() > --------------------------------------- -- _____________ Maric Michaud -- http://mail.python.org/mailman/listinfo/python-list