python 装饰器语法糖
时间: 2025-01-08 20:00:48 AIGC 浏览: 50
### 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_hello():
print("Hello!")
say_hello()
```
这段代码展示了如何使用 `@` 语法糖将 `say_hello()` 函数传递给 `my_decorator()` 进行封装[^3]。
#### 参数化的装饰器
如果希望装饰器能够接收参数,则可以通过嵌套一层闭包结构实现更为灵活的功能定制:
```python
import functools
def repeat(num_times):
def decorator_repeat(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(num_times):
value = func(*args, **kwargs)
return value
return wrapper
return decorator_repeat
@repeat(num_times=4)
def greet(name):
print(f"Hello {name}")
greet("Alice")
```
此例子中,`repeat()` 是一个带有参数的高阶装饰器,它可以控制目标函数被执行的具体次数[^1]。
#### 类装饰器应用
除了普通的函数装饰器外,Python 同样允许使用类作为装饰器对象。此类需重写 `__call__` 方法以便能够在调用时生效:
```python
class CountCalls:
def __init__(self, func):
self.func = func
self.num_calls = 0
def __call__(self, *args, **kwargs):
self.num_calls += 1
print(f"This is call #{self.num_calls} of {self.func.__name__!r}")
return self.func(*args, **kwargs)
@CountCalls
def say_goodbye(person="world"):
print(f"Goodbye, {person}")
say_goodbye()
say_goodbye("Bob")
```
上述代码片段说明了怎样构建并运用基于类形式的计数型装饰器[^4]。
阅读全文
相关推荐


















