@chengweihuang
2019-04-19T01:50:35.000000Z
字数 2025
阅读 471
每日总结
装饰器实际上就是为了给某程序增添功能,但该程序已经上线或已经被使用,那么就不能大批量的修改源代码,这样是不科学的也是不现实的,因为就产生了装饰器.
import timedef test():time.sleep(2)print("test is running!")test()
高阶函数
import timedef test():time.sleep(2)print("test is running!")def deco(func):start = time.time()func() #2stop = time.time()print(stop-start)deco(test)
我们看到似乎是达到了需求,即执行了源程序,同时也附加了计时功能,但是这只满足了一个要求(不能修改被装饰的函数的源代码)
但这修改了调用方式。假设不修改调用方式,那么在这样的程序中,被装饰函数就无法传递到另一个装饰函数中去。
import timedef test():time.sleep(2)print("test is running!")def deco(func):print(func)return funct = deco(test)test()
def func1():def func2():passdef func1():func2()
嵌套函数指的是在函数内部定义一个函数,而不是调用
函数只能调用和它同级别以及上级的变量或函数。也就是说:里面的能调用和它缩进一样的和他外部的,而内部的是无法调用的。
import timedef timer(func) :def deco():start = time.time()func()stop = time.time()print(stop-start)return decodef test():time.sleep(2)print("test is running!")goo = timer(test)goo()
实现了装饰器的作用
把函数看成是盒子,test是小盒子,deco是中盒子,timer是大盒子。程序中,把小盒子test传递到大盒子temer中的中盒子deco,然后再把中盒子deco拿出来,打开看看(调用)
每次都需要 goo = timer(test) 太麻烦
import timedef timer(func):def deco():start = time.time()func()stop = time.time()print(stop-start)return deco@timerdef test():time.sleep(2)print("test is running!")test()
通过闭包 , 将被装饰的函数 放到装饰器里面 ,来实现 不改变函数 ,也不改变函数的调用. 使函数增加新的功能
有参数的时候 怎么处理
import timedef timer(func):def deco(*args, **kwargs):start = time.time()func(*args, **kwargs)stop = time.time()print(stop-start)return deco@timerdef test(parameter):print("test is running!",parameter)test(1)
有返回值得时候
import timedef timer(func):def deco(*args, **kwargs):start = time.time()result = func(*args, **kwargs)stop = time.time()print(stop-start)return resultreturn deco@timerdef test(parameter):print("test is running!",parameter)return 666over = test(1)print(over)
装饰器有参数的时候
import timedef timer(name):def time2r(func):def deco(*args, **kwargs):start = time.time()result = func(*args, **kwargs)stop = time.time()print(name,stop - start)return resultreturn decoreturn time2r@timer('test1')def test1(parameter):print("test is running!", parameter)return 666@timer('test2')def test2(parameter):print("test is running!", parameter)return 999over = test1(1)over2 = test2(2)print(over)print(over2)