Python学习笔记:高阶函数(函数指针)与装饰器
来源:互联网 发布:mac 双定制粉底液 肤质 编辑:程序博客网 时间:2024/06/08 07:12
高阶函数
函数指针作为参数
函数可以作为参数传递给另一个函数,这是通过函数指针来实现的。在Python中,这称为高阶函数,函数名即为函数指针:
def func_1(): print("func_1 start running.") print("func_1 runs over.")def func_2(func): func()print("addr of func1():{}".format(func_1)) #函数名即为函数指针func_2(func_1)new_func=func_1 #此处的new_func相当于函数指针new_func()
函数指针作为返回值
def func_1(): print("func_1 start running.") print("func_1 runs over.")def func_2(func): print("this is a append feature.") return funcfunc_1=func_2(func_1) #此时func_2会运行func_1()
装饰器
装饰器是一种能为已有函数添加附加功能、又不会改变原函数的源码与调用方式的器具。可以看到上面函数指针作为返回值的代码段实现了添加功能又不改变源码与调用方式,但是实际上fun_2()与fun_1()不是在同一语句下执行的,fun_2()先于fun_1()执行。为实现原函数与装饰器同语句执行,可在fun_2()中再嵌套一层函数。
实现
import timedef timer(func): def decorator(): start_time=time.time() func() end_time=time.time() print("running time:{}".format(end_time-start_time)) return decoratordef fun_1(): print("fun_1 starts running...") print("fun_1 runs over")fun_1=timer(fun_1)fun_1()
在timer()中并没有实际的执行语句,它只是返回了一个装饰器的函数指针。fun_1=timer(fun_1)
语句将decorator()的函数地址覆盖了原函数fun_1()的地址,所以当执行fun_1()
时,实际上执行的是decorator()。这样就实现了装饰器的功能。
Python装饰器
在Python中,调用装饰器的方法为在需要装饰的函数定义前面使用@装饰器
,上述代码可改为:
import timedef timer(func): def decorator(): start_time=time.time() func() end_time=time.time() print("running time:{}".format(end_time-start_time)) return decorator@timerdef fun_1(): print("fun_1 starts running...") time.sleep(3) print("fun_1 runs over")fun_1()
带参数的函数
以上讨论的均是无参函数,若带参数的函数也需要用装饰器,则需要对装饰器代码进行修改。为使装饰器适应不同参数个数的函数,在装饰器中使用可变参数:
import timedef timer(func): def decorator(*args, **kwargs): start_time=time.time() func(*args, **kwargs) end_time=time.time() print("running time:{}".format(end_time-start_time)) return decorator@timerdef fun_1(arg1,arg2): print("fun_1 starts running...") time.sleep(1) print("fun_1 runs over")fun_1(1,2)
带参数的装饰器
阅读全文
0 0
- Python学习笔记:高阶函数(函数指针)与装饰器
- python 学习笔记---匿名函数 装饰器 偏函数
- python学习笔记,返回函数,匿名函数,装饰器
- python 函数装饰器学习
- Python学习笔记 - 高阶函数
- Python学习笔记----高阶函数
- python基础—(高阶,匿名,偏)函数 | 装饰器
- 装饰器,高阶函数,嵌套函数
- 【Python学习笔记】函数式编程:装饰器
- python学习笔记 匿名函数和装饰器
- 《Fluent Python》学习笔记 chpter7函数装饰器
- ES7装饰器、高阶函数与类
- python 学习笔记---函数式编程之高阶函数
- 【Python学习笔记】函数式编程:高阶函数
- 【Python学习笔记】函数式编程:高阶函数filter
- 【Python学习笔记】函数式编程:高阶函数sorted
- Python学习笔记,函数式编程,高阶函数
- Python函数式编程(高阶函数 <map/reduce filter sorted> 返回函数 匿名函数 装饰器 偏函数)
- JZOJ 5267. 费马点问题
- bzoj 4530(DFS序+线段树合并)
- 9.28-9.29 课程记录
- 小薇学院任务一:零基础HTML编码(笔记)
- bzoj 1966: [Ahoi2005]VIRUS 病毒检测
- Python学习笔记:高阶函数(函数指针)与装饰器
- MySQL之DML语句(上)
- 梯度下降法的三种形式BGD、SGD以及MBGD
- BZOJ 2115 Xor 线性基介绍(高斯消元 xor线性基)
- AJAX提交到Handler.ashx一般处理程序返回json数据 (字符串拼接方式)
- 11、C#里面随机数的获取、取最大数的实例
- 五子棋优化算法
- mysql基本操作
- 感知与记忆