What is a Python decorator?

What is a Python decorator?

By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

A decorator is just a regular Python function.

Put simply:?decorators wrap a function, modifying its behavior.

Python allows you to?use decorators in a simpler way with the?@?symbol, sometimes called the?“pie” syntax. The following example shows the syntax of a simple decorator.

Python decorator template




So,?@my_decorator?is just an easier way of saying?say_whee = my_decorator(say_whee). It’s how you apply a decorator to a function.

No alt text provided for this image


Can you guess what happens when you call?say_whee()? Try it:

No alt text provided for this image



You can now use this new decorator in other files by doing a regular?import.

To learn more about Python decorators, check this excellent tutorial on Real Python site

https://realpython.com/primer-on-python-decorators/

#python #realpython #programming

要查看或添加评论,请登录

Yamil Garcia的更多文章

社区洞察

其他会员也浏览了