Python连载19-装饰器
2020-12-13 04:52
标签:高阶函数 测试 wrap 括号 返回 技术 mic alt 函数名 一、检视一个函数相同的另一种方法 利用属性:函数._name 从结果来看他们的本体都是hello函数 二、装饰器 1.定义:在不改动代码的基础上无限扩展函数功能的一种机制,本质上来讲,装饰器是一个返回函数的高阶函数。 2.装饰器的使用:使用@愈发,即在每次要扩展到函数定义前使用@+函数名。 (1)装饰器的好处是,一旦定义,则可以装饰任意函数 4.上面对函数的装饰使用了系统定义的语法糖,下面开始手动执行一下装饰器 5.遗留问题: 为什么出来了两个时间戳 三、源码: d20_3_wrapper 地址:https://github.com/ruigege66/Python_learning/blob/master/d20_3_wrapper 2.CSDN:https://blog.csdn.net/weixin_44630050(心悦君兮君不知-睿) 3.博客园:https://www.cnblogs.com/ruigege0000/ 4.欢迎关注微信公众号:傅里叶变换,后台回复”礼包“,获取大数据学习资料 Python连载19-装饰器 标签:高阶函数 测试 wrap 括号 返回 技术 mic alt 函数名 原文地址:https://www.cnblogs.com/ruigege0000/p/11124053.htmldef hello():
print("我是一个测试程序")
f = hello
print(f.__name__)
print(hello.__name__)
import time
#对hello函数进行功能扩展,每次执行hello前打印时间
def printTime(f):
# 高阶函数,以函数作为参数
def wrapper(*args,**kwargs):
print("Time:",time.ctime())
return f(*args,**kwargs)
return wrapper
#上面定义了装饰器,使用的时候需要用到@符号,此符号是python语法
@printTime
def hello():
print("Hello World")
hello()
3.装饰器的好处:
(2)一旦被其装饰,则把装饰器的功能直接添加在定义函数的功能上.......复用了上面的代码........
def hello3():
print("厉害")
hello3 = printTime(hello3)
#这是向printTime传参hello3,然后返回wrapper,也就是hello3 = wrapper
hello3()
#执行了hello3函数,也就是执行了wrapper函数,先打印了“厉害”然后返回了最开始的hello3,但是后面有括号就是执行了最开始的
#hello3(),打印了厉害
aa = printTime(hello3)
aa()