Python dynamically gets the method of the currently running class name and function name _python

Source: Internet
Author: User
Tags in python

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:
Def a ():p
a.__name__

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.