python修饰器的实例代码
时间: 2023-02-24 19:34:10 浏览: 115
python类装饰器用法实例
以下是一个简单的 Python 修饰器的示例代码:
```python
def my_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
@my_decorator
def say_whee():
print("Whee!")
say_whee()
```
输出:
```
Something is happening before the function is called.
Whee!
Something is happening after the function is called.
```
该示例中,我们定义了一个名为 `my_decorator` 的修饰器函数,它接受一个函数作为参数,并返回一个新函数 (即包装器函数)。我们使用 `@my_decorator` 装饰器语法在 `say_whee` 函数上应用了该修饰器,这样在调用 `say_whee` 时,它会先输出 "Something is happening before the function is called.",然后调用 `say_whee` 函数本身,最后输出 "Something is happening after the function is called."。
阅读全文