python装饰器
2022/2/13 17:18:15
本文主要是介绍python装饰器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
""" 1.什么是装饰器: 装饰函数或者类,对函数或类进行功能的扩展 函数装饰器就是一个闭包函数 装饰器包含函数装饰器和类装饰器 函数装饰器带参数实质就是在外面在包裹一个函数 当有多个装饰器时先执行最里面的装饰器,最后执行最外面的(就近原则) """ import logging import time def runTime(func): def wrapper(*args,**kwargs): start_time = time.time() #执行原函数功能 func(*args,**kwargs) time.sleep(1) end_time = time.time() const = end_time - start_time print(f"统计{func.__name__}函数耗时{const}秒") return wrapper def testLog(func): def get_logger(): logger = logging.getLogger("logger") logger.setLevel("DEBUG") if not logger.handlers: path = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) fh = logging.FileHandler(path + ".log", encoding="utf-8") fmt = logging.Formatter("%(asctime)s %(filename)s:%(lineno)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S") fh.setFormatter(fmt) logger.addHandler(fh) return logger def wrapper(*args, **kwargs): try: func(*args, **kwargs) get_logger().info("执行成功") except Exception as e: get_logger().error(str(e)) return wrapper @runTime def welcome_vip(): print("欢迎来到vip") @runTime def fun2(a,b): sum = a + b print(f"执行函数2,sum={sum}") @runTime def fun3(a,b,c): sum = a + b + c print(f"执行函数3,sum={sum}") @testLog def fun4(a,b,c): sum = a+ b + c print(f"执行函数4,sum={sum}") if __name__ == '__main__': # welcome_vip() # fun2(1,2) # fun3(1,2,3) fun4(1,2) """类装饰器""" class Demo: def __init__(self,func): self.func = func #实例(),自动执行__call__方法 def __call__(self, *args, **kwargs): print("执行__call__方法") #执行被装饰的函数功能 self.func() #扩展功能 print(f"执行了{self.func.__name__}扩展功能") @Demo def test(): print("执行test函数") #原函数功能+扩展功能 # test = Demo(test) # test() def a(func): def wrapper(): func() print("a") return wrapper def b(func): def wrapper(): func() print("b") return wrapper def c(func): def wrapper(): func() print("c") return wrapper @c @b @a def test(): pass test() #结果a b c
这篇关于python装饰器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战
- 2024-09-18Python量化交易:入门指南与实践
- 2024-09-18Python量化交易:入门指南与实战技巧
- 2024-09-14Python人工智能项目实战:从零开始的实践指南
- 2024-09-14探索Python人工智能资料:初学者的指南
- 2024-09-14Python人工智能资料:初学者的全面指南
- 2024-09-13Matplotlib入门:轻松绘制Python数据可视化图表
- 2024-09-13Python人工智能:初学者的入门指南
- 2024-09-13Python人工智能:轻松入门与实践