# 装饰器:
# 定义:本质是函数,(装饰其他函数)就是为
# 其他函数添加附加功能
# 原则:1.不能修改被装饰的函数的源代码
# 2.不能修改被装饰的函数的调用方式
# 装饰器对被装饰的函数是透明的
import time def timmer(func): def warpper(*args,**kwargs): start_time=time.time() func() stop_time=time.time() print(‘the func run time is %s‘%(stop_time-start_time)) return warpper @timmer def test1(): time.sleep(3) print(‘in the test1‘) test1()
#TypeError: ‘NoneType‘ object is not callable
#解决办法:这是在调用函数时没有 return造成的,只要在函数中加入return即可解决
#如果你的函数有返回,但为何还会发生异常,是格式对应的不正确导致的!
# 2.高阶函数
# a:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
# b:返回值中包含函数名(不修改函数的调用方式)
import time def bar(): time.sleep(3) print(‘int the bar‘) def test2(func): print(func) return func #print(test2(bar)) bar=test2(bar) bar()
3.嵌套函数
def foo(): print(‘in the foo‘) def bar(): print(‘int the bar‘) bar() foo()
高阶函数+嵌套函数=装饰器
import time #func:传一个旧函数作为参数,传进去然后给你返回新函数,新函数对原来的函数进行升级改造 def timer(func): #timer(test1) func=test1 ‘‘‘ 用来对其他函数进行扩展,使其他函数可以在打印出函数执行的时间 ‘‘‘ #创建一个新函数 def deco(*args,**kwargs): start_time=time.time() func(*args,**kwargs) #run test1 #return func stop_time=time.time() print("the func run time is %s"%(stop_time-start_time)) #返回新函数 return deco # 把test1作为参数传递给了timer(),此时,在timer()内部,func = test1,接下来, # 定义了一个wrapper()函数,但并未调用,只是在内存中保存了,并且 # 标签为wrapper。在timer()函数的最后返回wrapper()函数的内存地址wrapper。 # 然后再把wrapper赋值给了test1,那么此时test1已经不是原来的test1了, # 也就是test1原来的那些函数体的标签换掉了,换成了wrapper,运行test1()就是运行wrapper() @timer # = test1=timer(test1) def test1(): time.sleep(3) print(‘int the test1‘) test1()
原文:https://www.cnblogs.com/wengshaohang/p/12332291.html