import time
defcaculateTime(func):
startTime = time.time()
func()
print(time.time() - startTime )
defbeHandsome():
print('i will be handsome')
caculateTime(beHandsome) # 若干个函数就作为参数传递给caculateTime()
2、装饰器开始
2.1优化1.3代码
import time
defbeHandsome():
print('i will be handsome')
defcaculateTime(func):definner():# 定义内部函数
startTime = time.time()
func()
print(time.time() - startTime )
return inner # 返回内部函数
beHandsome = caculateTime(beHandsome)
beHandsome()
# 装饰器初具规模,唯一不完美是还要在做一次赋值调用
2.2再优化
import time
defcaculateTime(func):definner():
startTime = time.time()
func()
print(time.time() - startTime)
return inner
@caculateTime # 等价于 beHandsome= caculateTime(beHandsome) defbeHandsome():
print('i will be handsome')
beHandsome()
2.3总结
装饰器的本质:一个闭包函数
装饰器的功能:在不修改原函数及其调用方式的情况下对原函数功能进行扩展
3、高潮
3.1带参装饰器
import time
defcaculateTime(func):definner(name):# 单个参数
startTime = time.time()
func(name) # 单个参数
print(time.time() - startTime)
return inner
@caculateTime # 等价于 beHandsome = caculateTime(beHandsome) defbeHandsome(name):# 单个参数
print('%s will be handsome'%name)
beHandsome("hankin") # 单个参数
3.2带多个参且有返回值装饰器
import time
defcaculateTime(func):definner(*args,**kwargs):# 多个参数
startTime = time.time()
ret = func(*args,**kwargs) # 多个参数
print(time.time() - startTime)
return ret
return inner
@caculateTime defbeHandsome(name):
print('%s will be handsome'%name)
@caculateTime defbeHandsomeMan(name,sex):
print('%s will be a handsome %s'%(name,sex))
return'done'
beHandsome('hankin')
print(beHandsomeMan('hankin','man'))
4、结尾
4.1装饰器的一般结构
defcaculateTime(func):definner(*args,**kwargs):'''执行函数之前要做的'''
ret = func(*args,**kwargs)
'''执行函数之后要做的'''return ret
return inner
python函数——装饰器1、装饰器前奏1.1需求:chao(pm):hankin(人名)啊!写一个名为beHandsome的函数。hankin(coder):写完了,如下!def beHandsome(): print('i will be handsome')1.2需求变更chao(pm):hankin(人名)啊!统计一下beHandsome...