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

Source: Internet
Author: User

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

Copy CodeThe code is as follows: Def a ():p
a.__name__


In addition, you can:

Copy CodeThe 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:

Copy CodeThe 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.

Copy CodeThe 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

Copy CodeThe 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

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

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.