一,装饰器定义:本质就是函数,功能是为其他函数添加新功能
原则:
1.不修改被装饰函数的源代码(开放封闭原则)
2.为被装饰函数添加新功能后,不修改被修饰函数的调用方式
3.装饰器=高阶函数+函数嵌套+闭包
高阶函数定义:
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
闭包:在一个作用域里放入定义变量,相当于打了一个包
 #这就是一个实现一个装饰器最基本的架子
def timer(func): #函数接收的参数是一个函数名
def frame():
func()
return frame #函数的返回值是一个函数名
import time                           #时间模块计算func()运行的时间
def timer(func):
def frame(*args,**kwargs):#添加参数*args,**kwargs
start_time=time.time()
func(*args,**kwargs)
stop_time=time.time()
#添加简单功能
print('func函数[%s],运行时间是[%s]' %(func,stop_time-start_time)
return frame

给timer()添加一个return

import time
def timer(func):
def frame(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time=time.time()
print('func函数[%s],运行时间是[%s]' %(func,stop_time-start_time))
return res
return frame #给timer()添加的return来触发frame()来run

编写一个函数来使用我们的装饰器

@timer()#@timer就等同于run_def=timer(cal)
def run_def(simple):
print('This is a simple function')
res=0
for i in simple:
res+=1
return res
run_def(range(9))

#在使用pycharm的时候,在看不懂运行逻辑的时候,建议使用debug

最新文章

  1. 进击的Python【第二章】:Python基础(二)
  2. 第二章:搭建Android开发环境
  3. 关于 jquery 选择器的 深入理解 -1
  4. Unity脚本系统
  5. js让iframe高度自动
  6. 【leetcode】354. Russian Doll Envelopes
  7. Putty终端 模拟 远程登录 虚拟机Linux
  8. 在android客户端加载html源代码总结
  9. vim下编写html的超级利器emmet
  10. java 短信发送例子 2
  11. 软件协作工具Trello
  12. [置顶] cuzy sdk之起源
  13. SVN操作手册(part1&part2)——SVN安装
  14. TestNG+ExtentReports生成超漂亮的测试报告
  15. 使用Autofac,提示重写成员“Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(System.Type)”时违反了继承安全性规则。重写方法的安全可访问性必须与所重写方法的安全可访问性匹配。
  16. mysql 不同索引的区别和适用情况总结
  17. laravel带参数分页
  18. 洗礼灵魂,修炼python(89)-- 知识拾遗篇 —— 进程
  19. Codeforces 596D Wilbur and Trees dp (看题解)
  20. spoj mgame

热门文章

  1. idea 快捷键以及包含字符串文件搜索
  2. bzoj 2016: [Usaco2010]Chocolate Eating【二分+贪心】
  3. bzoj 2839: 集合计数【容斥原理+组合数学】
  4. Ubuntu18安装sublime 3
  5. Robot Framework问题汇总...不断更新中
  6. 校赛F 比比谁更快(线段树)
  7. github下载下来的C#控制台小游戏[含源码]
  8. 1、IO概述及File类
  9. 【LeetCode 33】Search in Rotated Sorted Array
  10. C# Equals的重写