Python中的函数装饰器:实例理解和应用场景
在 Python 中,函数装饰器是一种特殊类型的函数,它能够在不改变原函数定义的情况下,为原函数添加新的功能。
实例理解:
- 计时装饰器(@timeit):
```python
import timeit
原函数
def original_function():
time.sleep(1)
装饰器
@timeit.timeit
def decorated_function(func):
def wrapper():
func()
print(“Function execution time: “, wrapper.time_taken)
wrapper.time_taken = 0
return wrapper
original_function()
装饰器运行后,会在原函数执行前后打印出时间。
2. 访问控制装饰器(@auth_required):
```python
def auth_required(func):
def wrapper(*args, **kwargs):
if check_auth():
func(*args, **kwargs))
else:
print("Access denied!")
return wrapper
# 假设有一个 check_auth 实现的函数
def check_auth():
# 例如:模拟登录检查
return True
@auth_required
def protected_function():
print("This is a protected function!")
protected_function()
在保护函数周围使用 @auth_required
装饰器,会自动检查用户是否具备访问的权限。如果权限不足,程序将直接跳过装饰器并执行相应代码块。
还没有评论,来说两句吧...