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!")

实际应用

装饰器在实际开发中有很多应用场景,比如:

  • 日志记录
  • 性能测试
  • 权限验证
  • 缓存
0 0
分享文章
评论 (0)
登录 后发表评论
暂无评论

成为第一个评论的人吧!