first, use the built-in method and decorator method to get the class name, function name
The case for getting the name of a function in Python is internal, external, well-fetched from the outside, using the object pointing to the function, and then using the __name__ property
The code is as follows:
Def a ():p
a.__name__
In addition, you can:
The code is as follows:
GetAttr (A, ' __name__ ')
Although some take off the pants fart, in short, the method obtained from the outside is very flexible.
Some students need to use some tricks to get the name of the function itself from inside the function.
1. How to use the SYS module:
The code is as follows:
Def a ():
Print Sys._getframe (). F_code.co_name
F_code and Co_name can refer to the PYc generation and namespace chapters of Python source parsing.
2. How to use decorators:
Using decorators, you can point a function at a variable and then take the __name__ method of the Variable object.
The code is as follows:
def Timeit (func):
def run (*ARGV):
Print func.__name__
If argv:
ret = func (*ARGV)
Else
ret = func ()
return ret
return run
@timeit
Def t (a):
Print a
T (1)
Second, using the inspect module to dynamically get the currently running function name
The code is as follows:
Import Inspect
Def get_current_function_name ():
return Inspect.stack () [1][3]
Class MyClass:
def function_one (self):
Print "%s.%s invoked"% (self.__class__.__name__, get_current_function_name ())
if __name__ = = "__main__":
MyClass = MyClass ()
Myclass.function_one ()
It is convenient to dynamically get the name of the currently running function, especially for some debug systems