要理解什么是装饰器,您首先需要熟悉Python处理函数的方式。从它的观点来看,函数和对象没有什么不同。它们有属性,可以重新分配:
- def func():
- print('hello from func')
- func()
- > hello from func
- new_func = func
- new_func()
- > hello from func
- print(new_func.__name__)
- > func
此外,你还可以将它们作为参数传递给其他函数:
- def func():
- print('hello from func')
- def call_func_twice(callback):
- callback()
- callback()
- call_func_twice(func)
- > hello from func
- > hello from func
现在,我们介绍装饰器。装饰器(decorator)用于修改函数或类的行为。实现这一点的方法是定义一个返回另一个函数的函数(装饰器)。这听起来很复杂,但是通过这个例子你会理解所有的东西:
- def logging_decorator(func):
- def logging_wrapper(*args, **kwargs):
- print(f'Before {func.__name__}')
- func(*args, **kwargs)
- print(f'After {func.__name__}')
- return logging_wrapper
- @logging_decorator
- def sum(x, y):
- print(x + y)
- sum(2, 5)
- > Before sum
- > 7
- > After sum
让我们一步一步来: