装饰器,其实是用到了闭包的原理来进行操作的。
以下是一个简单的例子:
def outer(func):
print("OUTER enter ...")
def wrapper(*args, **kwargs):
print("调用之前......")
result = func(*args, **kwargs)
print("调用之后......")
return result
print("OUTER leave ...")
return wrapper
@outer
def my_hello():
print("hello world")
上面的代码可以运行出结果:
这个时候就会把这个闭包创建出来。
当我们调用my_hello函数的时候,会进行执行wrapper里的代码:
def outer(func):
print("OUTER enter ...")
def wrapper(*args, **kwargs):
print("调用之前......")
result = func(*args, **kwargs)
print("调用之后......")
return result
print("OUTER leave ...")
return wrapper
@outer
def my_hello():
print("hello world")
my_hello()
调用原理:
等价于:
def outer(func):
print("OUTER enter ...")
def wrapper(*args, **kwargs):
print("调用之前......")
result = func(*args, **kwargs)
print("调用之后......")
return result
print("OUTER leave ...")
return wrapper
# @outer
def my_hello():
print("hello world")
my_hello = outer(my_hello)
my_hello()
def outer1(func):
print("OUTER enter ...1")
def wrapper(*args, **kwargs):
print("调用之前......1")
result = func(*args, **kwargs)
print("调用之后......1")
return result
print("OUTER leave ...1")
return wrapper
def outer2(func):
print("OUTER enter ...2")
def wrapper(*args, **kwargs):
print("调用之前......2")
result = func(*args, **kwargs)
print("调用之后......2")
return result
print("OUTER leave ...2")
return wrapper
@outer1
@outer2
def my_hello():
print("hello world")
打印的结果如下:
调用的时候:
def outer1(func):
print("OUTER enter ...1")
def wrapper(*args, **kwargs):
print("调用之前......1")
result = func(*args, **kwargs)
print("调用之后......1")
return result
print("OUTER leave ...1")
return wrapper
def outer2(func):
print("OUTER enter ...2")
def wrapper(*args, **kwargs):
print("调用之前......2")
result = func(*args, **kwargs)
print("调用之后......2")
return result
print("OUTER leave ...2")
return wrapper
@outer1
@outer2
def my_hello():
print("hello world")
my_hello()
运行结果为:
调用原理:
def outer1(func):
print("OUTER enter ...1")
def wrapper(*args, **kwargs):
print("调用之前......1")
result = func(*args, **kwargs)
print("调用之后......1")
return result
print("OUTER leave ...1")
return wrapper
def outer2(func):
print("OUTER enter ...2")
def wrapper(*args, **kwargs):
print("调用之前......2")
result = func(*args, **kwargs)
print("调用之后......2")
return result
print("OUTER leave ...2")
return wrapper
# @outer1
# @outer2
def my_hello():
print("hello world")
my_hello = outer2(my_hello)
my_hello = outer1(my_hello)
my_hello()
运行结果如下: