在Python中,装饰器是一种特殊类型的函数,用于在不修改原始函数代码的情况下,给函数增加额外的功能。装饰器通过在函数定义前使用`@decorator_name`语法糖来应用。
```python
定义装饰器函数
def simple_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
使用装饰器
@simple_decorator
def say_hello():
print("Hello!")
调用被装饰的函数
say_hello()
输出:
```
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
在这个例子中,`simple_decorator`是一个装饰器,它在`say_hello`函数调用前后添加了一些额外的行为。
当你运行这段代码时,实际上是调用了`simple_decorator`返回的`wrapper`函数,而`wrapper`函数内部调用了原始的`say_hello`函数。