Python中的函数装饰器:实例理解和应用场景

原创 ﹏ヽ暗。殇╰゛Y 2025-03-05 20:06 31阅读 0赞

在 Python 中,函数装饰器是一种特殊类型的函数,它能够在不改变原函数定义的情况下,为原函数添加新的功能。

实例理解:

  1. 计时装饰器(@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()

  1. 装饰器运行后,会在原函数执行前后打印出时间。
  2. 2. 访问控制装饰器(@auth_required):
  3. ```python
  4. def auth_required(func):
  5. def wrapper(*args, **kwargs):
  6. if check_auth():
  7. func(*args, **kwargs))
  8. else:
  9. print("Access denied!")
  10. return wrapper
  11. # 假设有一个 check_auth 实现的函数
  12. def check_auth():
  13. # 例如:模拟登录检查
  14. return True
  15. @auth_required
  16. def protected_function():
  17. print("This is a protected function!")
  18. protected_function()

在保护函数周围使用 @auth_required 装饰器,会自动检查用户是否具备访问的权限。如果权限不足,程序将直接跳过装饰器并执行相应代码块。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,31人围观)

还没有评论,来说两句吧...

相关阅读