带参数的装饰器
时间: 2023-07-06 09:14:34 浏览: 45
Python 装饰器可以带有参数,这样可以在装饰器函数中定制不同的装饰行为。带参数的装饰器的语法格式如下:
```python
def decorator(*args, **kwargs):
def wrapper(func):
def inner_wrapper(*args, **kwargs):
# do something
return func(*args, **kwargs)
return inner_wrapper
return wrapper
```
其中,`decorator` 函数是一个带有参数的装饰器函数,它接收不定长的位置参数 `*args` 和不定长的关键字参数 `**kwargs`,并返回一个新的函数 `wrapper`。这个新函数 `wrapper` 接收一个函数对象 `func` 作为参数,并返回一个新的函数 `inner_wrapper`,该函数包装了原函数 `func` 并增加了一些新的功能。
例如,下面是一个带参数的装饰器示例:
```python
def repeat(num):
def decorator(func):
def wrapper(*args, **kwargs):
for i in range(num):
print(f"Repeat {i + 1} times:")
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(num=3)
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Tom")
```
该示例中,`repeat` 是一个带有参数 `num` 的装饰器函数,它返回一个新的函数 `decorator`。在 `decorator` 函数中定义了一个新的函数 `wrapper`,该函数包装了原函数 `func`,并在函数执行前后进行了多次重复的操作。在函数 `say_hello` 上加上装饰器 `@repeat(num=3)`,意味着 `say_hello` 函数将被 `repeat` 装饰器包装,并执行三次重复的操作。
当代码运行时,输出结果如下:
```
Repeat 1 times:
Hello, Tom!
Repeat 2 times:
Hello, Tom!
Repeat 3 times:
Hello, Tom!
```
可以看到,带参数的装饰器 `repeat` 成功地包装了函数 `say_hello`,并在函数执行前后进行了多次重复的操作。