1、本质
装饰器本质上就是一个函数,在不修改源代码,调用方法的前提下,用来给其他函数添加功能的函数
2、实例
如果我们有一个这样的函数,打印输出hello decorator
def test1():
print('-----hello decorator -----')
但是,我们想在不修改函数源代码,不修改调用方法前提下,增加一个打印语句hello world
我们需要再次定义一个函数:而这个函数,就是一个最简单的装饰器:
def warpper(func):
def inner():
print('hello world')
func()
return inner
warpper函数内嵌inner函数,最后返回inner函数,可是,这个函数怎么用呢?
你肯定已经看出来warpper函数参数是一个函数,在inner函数内部进行调用
所以,我们可以这样用:
warpper(test1)
但是这样肯定不行的,返回值是一个函数的引用,所以需要用一个变量名来存储,然后加上小括号调用
func = warpper(test1)
func()
# -------------output( hello world \n hello decorator )
这就完成了函数的装饰, 但是调用方法改变了,原来的test1改成了func(),所以做以下修改:
func() = warpper # 改成 test1 = warpper(test1)
func() # 改成test1()
已经完成了99%了,最后用python提供的语法糖就行了
类似于这样 – @function_name
# 第一过程最终代码展示
def warpper(func):
def inner():
print('hello world')
func()
return inner
@warpper
def test():
print('hello decorator ')
test()
引用好文,见链接
https://www.cnblogs.com/jedenzhan/p/8683476.html