深入理解Python的装饰器:案例和应用
装饰器是 Python 中一种强大的语言特性,它允许我们在不改变原函数代码的情况下,添加或修改函数的行为。
下面通过几个实际的案例来理解和应用装饰器:
- 计时器:
```python
import time
def timer(func):
def wrapper(args, **kwargs):
start_time = time.time()
result = func(args, **kwargs))
endtime = time.time()
print(f’Func {func._name} took {end_time - start_time:.3f} seconds.’)
return result
return wrapper
@timer
def slow_function(n):
time.sleep(n/10)
return n * n
print(slow_function(5)) # Output: Func slow_function took 2.498 seconds.
在这个例子中,我们定义了一个装饰器 `timer`。当我们将这个装饰器应用到 `slow_function` 上时,实际上是在原函数前添加了计时的功能。
2. 缓存结果:
```python
from functools import lru_cache
@lru_cache(maxsize=10) # Cache results up to 10 items
def power(n, m=None):
if m is None:
return n ** m
else:
result = 1
for _ in range(m):
result *= power(n)
return result
print(power(2, 3))) # Output: 8.0
在这个例子中,我们使用了 Python 内置的 functools.lru_cache
来实现缓存结果的功能。这样,当同一个参数 m 遇到多次求幂时,就会从缓存中获取结果,而不是重新计算。
总结来说,装饰器是Python面向对象编程中的一个重要工具,它允许我们在不修改原代码的情况下,对函数进行扩展和增强。
还没有评论,来说两句吧...