Getting method name from within the class method
George Sakkis
george.sakkis at gmail.com
Thu Oct 19 00:01:36 EDT 2006
Mitko Haralanov wrote:
> On 18 Oct 2006 14:38:12 -0700
> yellowalienbaby at gmail.com wrote:
>
> > >>> class test(object):
> > ... def a_method(self,this,that):
> > ... print self.a_method.__name__
>
> Doing the above will obviously work!
>
> However, I don't want to have to use the name of the function in the
> print statement (the ".a_method." part). Imagine having about 100 of
> the above print statements in the function and then you change the name
> of the function. I want all 100 of the print statements to work without
> having to change every one of them to reflect the new function name.
from inspect import getframeinfo,currentframe
class test(object):
def a_method(self,this,that):
print getframeinfo(currentframe())[2]
If you *really* have about 100 functions or methods you want to print
their names, don't copy and paste this all over the place; use a
decorator instead so that you can just write:
class test(object):
@print_name
def a_method(self,this,that):
pass
@print_name
def b_method(self,this,that):
pass
The definition of print_name is left as an exercise to the reader.
HTH,
George
More information about the Python-list
mailing list