python装饰器管理函数和类的注意点

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、注意点

(1)用装饰器修饰的函数或类主要应用场景,分为直接返回原始函数(类)和嵌套定义的代理函数对象。

(2)若直接返回园函数或类,则可确保修饰前后的数据属性一致,并能获得原始数据的属性信息。

(3)若返回的是包装原函数或类代理函数对象,则此时数据属性便发生变化,这种情况下一般多适用于调用。

2、实例

#传统写法,每一个方法都调用了logging方法来做日志的收集,冗余,改起来还麻烦;
classTestDecorator:

defprint_title(self):
logging();
print("hello我是title");

defprint_url(self):
logging();
print("hello我是url");

deflogging():
importinspect
#python内置的inspect.stack方法可以将你引用的模块文件信息保留在里面,返回的是一个数据的数据形式
method_name=inspect.stack()[1][3];
print("Logger-info进入方法={}".format(method_name))

defmain():
decorator=TestDecorator();
decorator.print_title();
decorator.print_url();

if__name__=='__main__':
main();