Getting method name from within the class method

Fredrik Lundh fredrik at pythonware.com
Thu Oct 19 08:16:57 CEST 2006


Mitko Haralanov wrote:

>>>>> class test(object):  
>> ...  def a_method(self,this,that):
>> ...   print self.a_method.__name__
> 
> Doing the above will obviously work!

so will

     print "a_method"

of course.  no need to be silly when you don't have to.

> 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.

why are you writing functions that needs to output their own name a
100 times?  why should the program's *external* behaviour depend on
such an irrelevant detail of its internal design?  sounds like lousy 
design to me.

if you want to tag 100 messages with the same name, and you want to make 
it easy to change that name, should the need arise, use a variable:

    def a_method(self, this, that):
        name = "myname"

        print name, "is running"
        print name, "is about to return"

</F>




More information about the Python-list mailing list