Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to a method name from with a method in Python?

Tags:

People also ask

How do you call methods in Python?

Function Calling in Python Once a function is created in Python, we can call it by writing function_name() itself or another function/ nested function. Following is the syntax for calling a function. Syntax: def function_name():

How do you get a function name inside a function in Python?

Method 1: Get Function Name in Python using function. func_name.

What is __ name __ in Python?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.


Say I have the following class defined with the method foo:

class MyClass:
    def foo(self):
        print "My name is %s" % __name__

Now when I call foo() I expect/want to see this printed out

My name is foo  

However I get

My name is __main__  

And if I was to put the class definition into a module called FooBar I would get

My name is FooBar  

However if I do

m = MyClass()
print m.foo.__name__

I get exactly what I want which is

My name is foo

Can someone please help explain why __name__ refers to the module and not the method name ? Is there an easy way to get the method name?

Many thanks