Python3 by class methods, class name corresponding to the function to obtain

 Today write code to pass a few parameters, like in the decorator to get a class where the function by passing the function, stackoverflow gives the answer

Python3 by function __qualname__ acquisition like properties

It is said Python2 can use im_class

Complete sample code:

from functools import wraps

def decorater(func):  
    @wraps(func)#保持原函数名不变
    def wrapper(*args,**kwargs):
        res=func(*args,**kwargs)
        print('装饰器内函数名:%s'%func.__name__)
        print('返回值:%s'%res)
        print('函数func所属的类:%s'%func.__qualname__)
        return res
    return wrapper


class Name():
    @decorater
    def func(self,*args,**kwargs):
        print('位置参数:{}'.format(args))
        print('关键字参数:{}'.format(kwargs))
        return 'return'

if __name__ == '__main__':
    a=Name()
    a.func(1,2,a=3,b=4)
    print('装饰外内函数名:%s' % a.func.__name__)


Print Results:

Positional parameters: (1, 2)
Keyword parameters: { 'a': 3, 'b': 4}
interior decorator function name: func
Return Value: return
type of the function func belongs: Name.func
outer decorative function name : wrapper

You can obtain a work function corresponding to the class and function names: Name.func

reference:

https://stackoverflow.com/a/40953053/9917670

https://docs.python.org/3/library/inspect.html#types-and-members

Published 115 original articles · won praise 34 · views 90000 +

Guess you like

Origin blog.csdn.net/u011519550/article/details/103051208