First, use the built-in method and the decorator method to get the class name, function name
The case of getting a function name in Python is divided into internal and external, from the outside to get, using the object pointing to the function, and then using the __name__ property
Copy Code code as follows:
In addition, you can also:
Copy Code code as follows:
GetAttr (A, ' __name__ ')
Although some pants fart, in short, the external acquisition method is very flexible.
Some students need to get the name of the function from the inside of the function, you need to use some skills.
1. Methods for using the SYS module:
Copy Code code 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 the Python source resolution.
2. How to use modifiers:
You can use a modifier to point a variable to a function, and then take the __name__ method of the Variable object.
Copy Code code 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)
Using inspect module to dynamically get the currently running function name
Copy Code code 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 currently running function name, especially for some debug systems