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,装饰器
0
投稿
猜你喜欢
Keras自定义实现带masking的meanpooling层方式
2021-06-23 03:29:47
Python 平方列表中每个数字的多种操作
2023-11-14 03:53:00
向Oracle数据库的CLOB属性插入数据报字符串过长错误
2023-07-23 11:11:06
python从入门到精通(DAY 3)
2023-11-03 08:23:18
Python爬虫入门案例之爬取二手房源数据
2021-07-13 15:31:41
python通过SSH登陆linux并操作的实现
2022-11-02 09:30:56
用SQL统计SQLServe表存储空间大小的代码
2012-06-06 19:52:22
交互设计实用指南系列(9)—一次点击
2010-02-08 12:42:00
如何得到数据库中所有表名 表字段及字段中文描述
2012-01-05 18:56:44
HTML5 Canvas 起步(1) - 基本概念
2009-04-21 13:14:00
图文详解vscode配置运行php项目完整版
2023-05-28 22:56:03
php生成shtml类用法实例
2023-11-15 21:46:23
两个不太常用的 CSS Hack
2008-06-27 12:49:00
利用sort()和Math.random()实现元素的随机排列
2010-10-19 12:42:00
python中删除某个元素的方法解析
2021-02-02 00:05:40
推荐8款常用的Python GUI图形界面开发框架
2023-04-09 04:02:41
如何把数据库记录显示到列表框里去?
2009-11-06 13:48:00
python 定时器,实现每天凌晨3点执行的方法
2023-06-25 12:32:01
详解用Python为直方图绘制拟合曲线的两种方法
2021-06-15 23:58:08
python语言线程标准库threading.local解读总结
2023-12-22 18:18:07