the name of a method
Diez B. Roggisch
deets at nospam.web.de
Thu Jan 15 11:37:16 EST 2009
thomas.steffen75 at googlemail.com wrote:
> Hello,
>
> I have a Class:
>
> class myClass:
> def __init__(self):
> # do something
> print "name of class = " + self.__class__.__name__
>
> def myMethod(self):
> # do something
> print "name of method = " + "myMethod"
> return
>
> ...
>
> I print the name of the class with self.__class__.__name__ in
> __init__.
> I want to print also in every method of myClass the name of the
> method.
> How can I get the name? I would not like to write e.g. "myMethod". Is
> there a variable like self.__class__.__name__ for this?
> Thanks for your hints, Thomas
This can be done by inspecting the stackframes. Look into the module
inspect. This has also been discussed very often on this list, stackframe &
inspect should be good searchterms.
However, if what you are after is logging, you should take a look into the
logging module. it has many advantages over simple print-statements, and
amongst other things allows you to print out the enclosing callable name
when invoked ala
logger.debug("Some message.")
I strongly recommend using that. And at least you can of course peek into
the logging module's source to see how the extract that information.
Diez
More information about the Python-list
mailing list