知识点提取:
def my_decorator(func):
def wrapper():
print("hello")
func()
return wrapper
@my_decorator
def greet():
print("world")
#装饰器其实是这个函数
#greet = my_decorator(greet)
greet()
def my_decorator(func):
def wrapper(*args, **kwargs):
print("hello")
func(*args, **kwargs)
return wrapper
@my_decorator
def greet(msg):
print(msg)
#装饰器其实是这个函数
#greet = my_decorator(greet)
greet("world")
def repeat(num):
def my_decorator(func):
def wrapper(*args, **kwargs):
for i in range(num):
print('wrapper of decorator')
func(*args, **kwargs)
return wrapper
return my_decorator
@repeat(4)
def greet(message):
print(message)
greet('hello world')
# 输出:wrapper of decoratorhello worldwrapper of decoratorhello worldwrapper of decoratorhello worldwrapper of decoratorhello world
@decorator1
@decorator2
@decorator3
def func():
…
它的执行顺序从里到外,所以上面的语句也等效于:
decorator1(decorator2(decorator3(func)))
import functools
def my_decorator1(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('execute decorator1')
func(*args, **kwargs)
return wrapper
def my_decorator2(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('execute decorator2')
func(*args, **kwargs)
return wrapper
@my_decorator1
@my_decorator2
def greet(message):
print(message)
greet('hello world')
#输出:
# execute decorator1
# execute decorator2
# hello world