装饰器
装饰器的本质:一个闭包函数
装饰器的功能:在不修改原函数及其调用方式的情况下对原函数功能进行扩展
修饰器详解请看:点击链接
(1)代码:外部的 f1 函数函数被彻底隐藏
代码:
def f1(x):
return x*2
def new_fn(f): #装饰器函数
def ff(x):
print("call" + f.__name__ + "()")
return f(x)
return ff
g = new_fn(f1)
print(g(5))
f1 = new_fn(f1)
print(f1(5))
#外部的 f1 函数函数被彻底隐藏
结果:
(2)有必加值时
代码:
import time
from functools import reduce
def performance(tt): # 当有必加的数值 或 字符串时 可以这样写 如必加字符 DEBUG
def d_performance(f): # 装饰器函数
def fa(*args, **kw): #接受多个参数,但知道几个参数时,可以不用最上面那个函数,
star = time.time() #装饰器本身不就是更改添加 python一些内置函数的模块中的函数中的一些功能吗
l = f(*args,**kw)
end = time.time()
print("[%s]call %s() in %f s" % (tt,f.__name__,(end-star)))
return l
return fa
return d_performance
@performance('DEBUG')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print (factorial(10))
(3)若装饰之后,不该不变原函数的属性、
请看代码:
import time,functools
from functools import reduce
def performance(tt):
def d_performance(f):
@functools.wraps(f) # 这一步为了不改变装饰过的factorial函数的属性,若不加上一步,你在下面输出
def fa(*args, **kw): #factorial.__name__的属性那么是 fa,若加上这一步,那么输出的是factorial,大家可以动手试一下
star = time.time()
l = f(*args,**kw)
end = time.time()
print("[%s]call %s() in %f s" % (tt,f.__name__,(end-star)))
return l
return fa
return d_performance
@performance('@decorator')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print (factorial(10))
print(factorial.__name__)