Читать книгу Professional Python - Luke Sneeringer - Страница 3
Part I
Functions
Chapter 1
Decorators
Understanding Decorators
ОглавлениеAt its core, a decorator is a callable that accepts a callable and returns a callable. A decorator is simply a function (or other callable, such as an object with a __call__
method) that accepts the decorated function as its positional argument. The decorator takes some action using that argument, and then either returns the original argument or some other callable (presumably that interacts with it in some way).
Because functions are first-class objects in Python, they can be passed to another function just as any other object can be. A decorator is just a function that expects another function, and does something with it.
This sounds more confusing than it actually is. Consider the following very simple decorator. It does nothing except append a line to the decorated callable's docstring.
Now, consider the following trivial function:
The function's docstring is the string specified in the first line. It is what you will see if you run help
on that function in the Python shell. Here is the decorator applied to the add
function:
Here is what you get if you run help
:
What has happened here is that the decorator made the modification to the function's __doc__
attribute, and then returned the original function object.