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._name}} took {end_time - start_time} seconds”)
return result
return wrapper
@timer
def my_function():
time.sleep(2)
my_function() # 输出: my_function took 2.0147365028937 seconds
2. 缓存装饰器:
```python
from functools import lru_cache
@lru_cache(maxsize=10) # 设置缓存大小
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(3)) # 输出: 3
print(fibonacci(4)) # 输出: 5
print(fibonacci(5)) # 输出: 8
理解:
装饰器是 Python 中一种高级语法,它允许在不改变已有代码结构的情况下,为函数、方法或者类添加新的功能。
装饰器使用 @decorator_name
的方式定义,并通过导入的装饰器进行应用。
还没有评论,来说两句吧...