黑松山资源网 Design By www.paidiu.com
本文实例讲述了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相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月07日
2024年10月07日
- 张宇.2001-替身【EMI百代】【WAV+CUE】
- 班得瑞原装进口《第六张新世纪专辑:日光海岸》1CD[APE/CUE分轨][339.5MB]
- 班得瑞原装进口《第七张新世纪专辑:梦花园》1CD[APE/CUE分轨][331.4MB]
- 班得瑞原装进口《第八张新世纪专辑:琉璃湖畔》1CD[APE/CUE分轨][286.4MB]
- 魏如萱.2011-在哪里(EP)【添翼创越】【WAV+CUE】
- 群星.1981-新金曲奖·青年创作园地12合辑(喜玛拉雅复刻版)【歌林】【WAV+CUE】
- 麦洁文.1989-新曲与精丫新艺宝】【WAV+CUE】
- SNH48《薄荷糖 (Mint Candy)》[320K/MP3][33.72MB]
- SNH48《薄荷糖 (Mint Candy)》[FLAC/分轨][78.59MB]
- 刘美麟《同生》[320K/MP3][70.99MB]
- 群星.1994-宝丽金最流行3CD【宝丽金】【WAV+CUE】
- 群星.2024-聆听“某某”影视原声带【华纳】【FLAC分轨】
- 陈慧娴.1989-永远是你的朋友(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 何洛洛.2024-别叫醒我(EP)【光羽】【FLAC分轨】
- 林忆莲.1996-爱莲说2CD【华纳】【WAV+CUE】