2 ответов
+ 3
"By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it." [Real Python]
A good way to understand decorators is writing one.
Decorators are also briefly explained in the Python Core course.
Python decorators:
https://www.sololearn.com/learn/Python/2463/?ref=app
https://www.sololearn.com/Course/Python/?ref=app
https://pythonbasics.org/decorators/
https://realpython.com/primer-on-python-decorators/
https://datagy.io/python-decorators/
+ 1
There are some particular cases when you want to give superpowers to the functions you are writing.
Some notable examples from the standard library:
@property
@staticmethod
@functools.lru_cache
@contextlib.contextmanager
You can write your own decorator too, for example to measure the execution time of your functions, you can find many tutorials online that cover this case.
For me, the caching decorator has proven to be the most useful.
https://code.sololearn.com/cWpFUu2kmHLZ/?ref=app
https://code.sololearn.com/cDT8ZI7T06of/?ref=app