国外的响应式网站模板,wordpress二开前端,高中信息技术课网站怎么做,网站开发有哪几类写在前面:python装饰器(fuctional decorators)就是用于拓展原来函数功能的一种函数#xff0c;目的是在不改变原函数名(或类名)的情况下#xff0c;给函数增加新的功能。 这个函数的特殊之处在于它的返回值也是一个函数#xff0c;这个函数是内嵌“原“”函数的函数。一般而…写在前面:python装饰器(fuctional decorators)就是用于拓展原来函数功能的一种函数目的是在不改变原函数名(或类名)的情况下给函数增加新的功能。 这个函数的特殊之处在于它的返回值也是一个函数这个函数是内嵌“原“”函数的函数。一般而言我们要想拓展原来函数代码最直接的办法就是侵入代码里面修改例如importtimedeff():print(hello)time.sleep(1)print(world)这是我们最原始的的一个函数然后我们试图记录下这个函数执行的总时间那最简单的做法就是改动原来的代码importtimedeff():start_timetime.time()print(hello)time.sleep(1)print(world)end_timetime.time()execution_time (end_time - start_time)*1000print(time is %d ms %execution_time)但是实际工作中有些时候核心代码并不可以直接去改所以在不改动原代码的情况下我们可以再定义一个函数。(但是生效需要再次执行函数)importtimedefdeco(func):start_timetime.time()func()end_timetime.time()execution_time (end_time - start_time)*1000print(time is %d ms %execution_time)deff():print(hello)time.sleep(1)print(world)if __name__ __main__:deco(f)print(f.__name__ is,f.__name__)print()这里我们定义了一个函数deco它的参数是一个函数然后给这个函数嵌入了计时功能。但是想要拓展这一千万个函数功能就是要执行一千万次deco()函数所以这样并不理想接下来我们可以试着用装饰器来实现先看看装饰器最原始的面貌。importtimedefdeco(f):defwrapper():start_timetime.time()f()end_timetime.time()execution_time (end_time - start_time)*1000print(time is %d ms %execution_time )returnwrapperdecodeff():print(hello)time.sleep(1)print(world)if __name__ __main__:f()这里的deco函数就是最原始的装饰器它的参数是一个函数然后返回值也是一个函数。其中作为参数的这个函数f()就在返回函数wrapper()的内部执行。然后在函数f()前面加上decof()函数就相当于被注入了计时功能现在只要调用f()它就已经变身为“新的功能更多”的函数了(不需要重复执行原函数)。扩展1带有固定参数的装饰器importtimedefdeco(f):defwrapper(a,b):start_timetime.time()f(a,b)end_timetime.time()execution_time (end_time - start_time)*1000print(time is %d ms %execution_time)returnwrapperdecodeff(a,b):print(be on)time.sleep(1)print(result is %d %(ab))if __name__ __main__:f(3,4)扩展2无固定参数的装饰器importtimedefdeco(f):def wrapper(*args, **kwargs):start_timetime.time()f(*args, **kwargs)end_timetime.time()execution_time_ (end_time - start_time)*1000print(time is %d ms %execution_time)returnwrapperdecodeff(a,b):print(be on)time.sleep(1)print(result is %d %(ab))decodeff2(a,b,c):print(be on)time.sleep(1)print(result is %d %(abc))if __name__ __main__:f2(3,4,5)f(3,4)扩展3使用多个装饰器装饰一个函数importtimedefdeco01(f):def wrapper(*args, **kwargs):print(this is deco01)start_timetime.time()f(*args, **kwargs)end_timetime.time()execution_time (end_time - start_time)*1000print(time is %d ms %execution_time)print(deco01 end here)returnwrapperdefdeco02(f):def wrapper(*args, **kwargs):print(this is deco02)f(*args, **kwargs)print(deco02 end here)returnwrapperdeco01deco02deff(a,b):print(hello,here is a func for add :)time.sleep(1)print(result is %d %(ab))if __name__ __main__:f(3,4)this is deco01this is deco02hellohere is a func for add :result is 7deco02 end heretime is 1003 msdeco01 end here装饰器调用顺序装饰器是可以叠加使用的那么使用装饰器以后代码是啥顺序呢对于Python中的””语法糖装饰器的调用顺序与使用 语法糖声明的顺序相反。在这个例子中”f(3, 4) deco01(deco02(f(3, 4)))”。