Conteúdo do Curso
Intermediate Python Techniques
Intermediate Python Techniques
Introduction to Decorators
Let's discuss decorators.
Note that decorators
can be a challenging topic for beginners. We will examine decorators in detail, step by step, explaining how they work. It might be challenging to grasp at first. Are you ready to tackle these challenges? That's why you're here!
Decorators
are functions that add extra functionality to another function, utilizing closures. Here is an example of how a decorator works:
def decorator(func): def wrapper(argument1, argument2): print("Function starts executing") result = func(argument1, argument2) print("Function ends executing") return result return wrapper def add(a, b): print(f"Function add: {a} + {b}") return a + b add = decorator(add) print(add(14, 12)) print(add(11, 28)) print(add(33, 16))
In this example, the decorator()
function takes another function as an argument, defines a wrapper()
function, encloses the given function within wrapper()
, and returns wrapper()
. There are three steps to a decorator's operation:
- Taking a function as an argument.
- Enclosing that function within a newly defined function (wrapper).
- Returning the wrapper function, which now encloses the original function.
The wrapper()
function contains the main logic of the decorator and invokes the function with the given parameters. The add()
function is reassigned by the wrapper()
function returned by decorator()
, which now contains the enclosed add()
function.
- The Python interpreter first reads and defines the decorator function. It doesn't execute any code inside the decorator at this point; it just makes a note that there's a function named decorator.
- Next, it defines the add function. Like decorator, this function is also not executed yet, just defined.
- After defining add, the next line
add = decorator(add)
is executed. This is where the decorator function is first called. It receives the add function as its argument. Inside thedecorator
, it defines thewrapper
and then returns it. So now,add
no longer refers to the originaladd
function but to thewrapper
function returned by thedecorator
. - When
add(14, 12)
is executed, it's calling the wrapper function with 14 and 12.
- wrapper prints "Function starts executing"
- Calls the original add function with 14 and 12, which prints "Function add: 14 + 12" and returns 26.
- Prints "Function ends executing".
wrapper
returns 26, which is printed by print(add(14, 12)).
The next calls repeat the previous steps.
Obrigado pelo seu feedback!