装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。
一个函数可以作为另一个函数的参数
##装饰器模板(1)、定义自己先要执行的函数
##(2)def new_fn(要执行的函数名字):
##def fn(要执行的参数函数参数/或者没有参数):
## 添加要添加的函数功能
## return f(x) 函数的执行结果
## return fn
##(3)、装饰器进行修饰
———————————————————————————————
##一个函数可以作为另一个函数的参数
import numpy as np
def greet(name):
return "Hello"+ name
def call_func(func):
other_name ="John"
return func(other_name)
print(call_func(greet))
输出:HelloJohn
函数可以返回其他函数
def get_text(name):##需要执行的函数
return "lorem ipsum,{0} dolor sit amet".format(name)
##装饰器
def p_decorate (func):
def func_wrapper(name):
return "<P>{0}</p>".format(func(name))
return func_wrapper
##
my_get_text=p_decorate(get_text)
print(my_get_text("John"))
输出:<P>lorem ipsum,John dolor sit amet</p>
这是我们的第一个装饰器。一个函数把另一个函数作为参数,生成一个新的函数。扩大原始函数的工作,并返回生成的函数,以便我们可以在调用。为了让get_text本身被P_decorate装饰,我们只需要将name配给get_text
def get_text(name):##需要执行的函数
return "lorem ipsum,{0} dolor sit amet".format(name)
def p_decorate (func):
def func_wrapper(name):
return "<P>{0}</p>".format(func(name))
return func_wrapper
get_text=p_decorate(get_text)
print(get_text("John"))
输出:<P>lorem ipsum,John dolor sit amet</p>
装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。