Python装饰器初探:理解和使用装饰器

原创 ╰+哭是因爲堅強的太久メ 2025-01-13 18:24 84阅读 0赞

装饰器是Python中一种强大的工具,它允许我们在不改变原函数代码的情况下,为其添加新的功能或者修改其行为。

在Python中,装饰器通常是一个接收一个函数作为输入,并返回一个新的函数的函数。例如:

  1. def my_decorator(func):
  2. def wrapper():
  3. print("Something is happening before the function is called.")
  4. func()
  5. print("Something is happening after the function is called.")
  6. return wrapper
  7. @my_decorator
  8. def say_hello():
  9. print("Hello!")
  10. say_hello()

在这个例子中,my_decorator是一个装饰器,它接收一个函数作为参数,并返回一个新的函数。当我们在say_hello函数前加上@my_decorator时,实际上是将say_hello函数传递给my_decorator来处理。

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

发表评论

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

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

相关阅读