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():
Method 1: Get Function Name in Python using function. func_name.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With