写一个python装饰器使用的代码示例
时间: 2024-02-08 14:39:30 浏览: 41
好的,我来给您提供一个简单的 Python 装饰器示例。
```python
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function is called.")
result = func(*args, **kwargs)
print("After function is called.")
return result
return wrapper
@my_decorator
def my_function():
print("Function is called.")
my_function()
```
在这个示例中,我们定义了一个名为 `my_decorator` 的装饰器函数,它接受一个函数作为参数,并返回一个新的函数。这个新的函数是 `wrapper`,它会在被装饰的函数执行前后打印一些信息,并最终返回被装饰函数的结果。
然后,我们使用 `@my_decorator` 语法将 `my_function` 函数装饰了起来。当调用 `my_function` 时,实际上是调用了 `wrapper` 函数,因为 `my_function` 已经被 `my_decorator` 装饰了。所以,当我们运行这段代码时,输出将会是:
```
Before function is called.
Function is called.
After function is called.
```