文章目录
前言
今天我们一起来学习python中的装饰器,要学习装饰器,我们首先要搞清楚函数嵌套和闭包相关的知识,如果对函数嵌套和闭包的知识搞清楚了的同学,可以直接阅读本文,如果对此还不清楚的,请阅读我的另一篇博文,【超详细解释】一文带你了解python中的函数嵌套和闭包。
好了,下面进入正文。
一、一个例子
我们先来看看一个简单的容易理解的例子。
def hi():
return "hi yasoob!"
def doSomethingBeforeHi(func):
print("I am doing some boring work before executing hi()")
print(func())
doSomethingBeforeHi(hi)
# outputs:I am doing some boring work before executing hi()
# hi yasoob!
我们上面这个小例子就是在一个函数中接受另一个函数作为参数。然后执行传进来的函数。
二、第一个装饰器
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
# a_new_decorator是一个嵌套函数,它接收一个函数作为变量,并且返回它的内嵌函数。
def a_function_requiring_decoration():#1
print("I am the function which needs some decoration to remove my foul smell")
# 这里定义了一个函数a_function_requiring_decoration
a_function_requiring_decoration()#2
# outputs: "I am the function which needs some decoration to remove my foul smell"
#这里是函数a_function_requiring_decoration的直接调用
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
# now a_function_requiring_decoration is wrapped by wrapTheFunction()
# 这里的a_function_requiring_decoration不是我们上面调用函数
#a_function_requiring_decoration了,这句话是调用函数a_new_decorator,并且这里函数的
#a_new_decorator的参数是函数#1,这里都是同名的函数,怕讲不清楚。好了,现在基本明白了,
#括号里面的是上面的函数,现在执行了函数a_new_decorator,它返回的是它的内嵌函数wrapTheFunction
a_function_requiring_decoration()
# outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
#那现在我们知道了再次调用函数a_function_requiring_decoration,其实执行的是函数wrapTheFunction
#因为进过执行后,a_function_requiring_decoration指向了函数wrapTheFunction的内存地址
这个装饰器,你看明白了吗?
这正是 python 中装饰器做的事情!它们封装一个函数,并且用这样或者那样的方式来修改它的行为。现在你也许疑惑,我们在代码里并没有使用 @ 符号?那只是一个简短的方式来生成一个被装饰的函数。
下面,我们来改写上面的代码。
def a_new_decorator(a_func):
def wrapTheFunction()