Python3.5装饰器典型案例分析
作者:loveliuzz 时间:2023-03-05 20:32:35
本文实例讲述了Python3.5装饰器。分享给大家供大家参考,具体如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#高阶函数+嵌套函数==>装饰器
import time
def timer(func): #timer(test1)-->func=test1
def decor():
start_time = time.time()
func() #run test1
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test1 = timer(test1)
def test1():
time.sleep(3)
print("in the test1")
@timer #test2 = timer(test2)
def test2():
time.sleep(3)
print("in the test2")
print(timer(test1)) #打印deco的地址
#test1 = timer(test1)
#test2 = timer(test2)
test1() #-->执行decor
test2()
运行结果:
<function timer.<locals>.decor at 0x00B720C0>
in the test1
the run time of func is 3.000171661376953
in the test2
the run time of func is 3.000171661376953
1、装饰器修饰有参数函数
#高阶函数+嵌套函数==>装饰器
import time
def timer(func): #timer(test1)-->func=test1
def decor(arg1,arg2):
start_time = time.time()
func(arg1,arg2) #run test2
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test2 = timer(test2) = decor test2(name)==>decor(name)
def test2(name,age):
print("test2:",name,age)
test2("liu",23)
运行结果 :
test2: liu 23
the run time of func is 0.0
2、装饰器修饰多个函数,有的函数带参数,有的函数不带参数的情况(采用参数组)
#高阶函数+嵌套函数==>装饰器
import time
def timer(func): #timer(test1)-->func=test1
def decor(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs) #run test1
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test1 = timer(test1)
def test1():
time.sleep(3)
print("in the test1")
@timer #test2 = timer(test2) = decor test2(name)==>decor(name)
def test2(name,age):
time.sleep(1)
print("test2:",name,age)
#test1 = timer(test1)
#test2 = timer(test2)
test1() #-->执行decor
test2("liu",23)
运行结果:
in the test1
the run time of func is 3.0036065578460693
test2: liu 23
the run time of func is 1.0084023475646973
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/loveliuzz/article/details/77878019
标签:Python3.5,装饰器


猜你喜欢
mysql创建Bitmap_Join_Indexes中的约束与索引
2024-01-15 18:25:50
JavaScript利用多彩线条摆出心形效果的示例代码
2024-04-16 10:29:49

ASP页面内VBScript和JScript的交互
2007-09-11 13:49:00
用Python编写个解释器实现方法接受
2023-01-11 15:50:08

python实现两个一维列表合并成一个二维列表
2023-08-06 12:59:44
如何基于js管理大文件上传及断点续传详析
2024-05-25 15:19:05

浏览器右下角弹出提示窗口
2008-10-30 12:37:00
Python数据结构与算法中的栈详解(2)
2022-02-11 07:00:51

Python 实现数据库更新脚本的生成方法
2024-01-15 22:35:43
教你使用python搭建一个QQ机器人实现叫起床服务
2021-04-22 02:25:41

如何提升JavaScript的运行速度(函数篇)
2010-05-17 13:27:00
生成Jupyter Lab快捷方式的小技巧
2022-11-29 11:55:42

MySQL数据库约束详解
2024-01-24 14:41:01

CSS技巧之圆角背景与三角形
2010-10-19 12:40:00
Python 寻找局部最高点的实现
2021-05-10 14:44:00
sqlserver中获取月份的天数的方法分享
2011-09-30 11:27:52
20行Python代码实现视频字符化功能
2023-01-08 21:17:02

PHP attributes()函数讲解
2023-06-04 09:33:02

Goland 的安装及激活教程(window、linux下安装)
2024-05-08 10:51:51

Python基于Socket实现简单聊天室
2022-06-13 11:56:51