If you want to learn what a decorator is, you must first know the composition of a decorator. It can be said that a decorator is composed of the following three aspects:
- Scope
Speaking of scope, it is actually the search order of L_E_G_B in Python. Look at the code.
a = abs(-2) #abs是Python内置的函数,其实这时的abs()就相当于是一个built-in变量
b = 3 #这就相当于是一个global变量
def one_function():
c = 1 #这就是一个enclosing变量
def two_function():
d = -1 #这就是一个local变量
e = c+b
return e
#比如说在函数two_function中,变量d中调用b,就会先在自身的函数中查找b这个变量,如果未查找到,则会进入上一层函数中进行查找,即one_function函数中查找b这个变量。
#查找到时被调用.如果未查找到,则会进入全局变量进行查找.
The second aspect about decorators is about higher-order functions
- Higher order function
First, let’s talk about the conditions of higher-order functions:
1. The function name can be assigned.
2. The function name can be used as a function parameter or as the return value of the function.
#首先创建一个函数
def add(x,y,f):
return f(x)+f(y)
#然后我们调用这个函数
add(-5,9,abs) #14
#等价于abs(-5)+abs(9)
- Closure
Next, let’s talk about closures
#接下来说一说闭包,首先我们创建一个函数
def foo3():
def inner():
return 8
return inner
#在这个函数中,我们如何得到8这个值呢,
foo3()()
8
inner()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'inner' is not defined