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

Python (179) 2023-06-22 22:05:51

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

1、注意点

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

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

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

2、实例

纯文本
复制到剪贴板
在新窗口中打开代码
EnlighterJS 3 Syntax Highlighter
#传统写法,每一个方法都调用了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();
#传统写法,每一个方法都调用了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();
#传统写法,每一个方法都调用了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();

以上就是python装饰器管理函数和类的注意点,希望能对大家有所帮助。

THE END

发表回复