This article mainly introduces how to obtain the currently running class name and function name dynamically in python, including the built-in method, sys module, modifier, and inspect module, for more information, see
1. Use the built-in method and modifier to obtain the class name and function name
In python, function names can be obtained from both internal and external sources. When the external conditions are good, the object pointing to the function is used and the _ name _ attribute is used.
The Code is as follows:
Def a (): pass
A. _ name __
In addition, you can:
The Code is as follows:
Getattr (a, '_ name __')
Despite some cases, the external method is flexible.
Some users need some skills to obtain the name of a function from the function itself.
1. How to Use the sys module:
The Code is as follows:
Def ():
Print sys. _ getframe (). f_code.co_name
For f_code and co_name, refer to the pyc generation and namespace chapter in python source code parsing.
2. How to Use the modifier:
You can use the modifier to point to a variable for the function, 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 ():
Print
T (1)
Ii. Use the inspect module to dynamically obtain the name of the currently running Function
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 obtain the name of the currently running function, especially for some debug systems.