Curso Python. Decoradores II. Vídeo 74
Introduction to Decorator Functions with Parameters
In this video, we will learn how to create decorators with parameters in Python. We start by modifying our previous decorator function to handle arguments and explore the use of asterisks (*) for handling an indeterminate number of parameters.
Modifying Addition and Subtraction Functions
- The addition and subtraction functions are modified to receive two parameters.
- The sum function now prints the sum of the two parameters.
- The subtract function returns the subtraction of the two parameters.
Creating a Decorator Function with Parameters
- To make our decorator function handle arguments, we use the convention of using asterisks (*) before a parameter name.
- This convention allows a function to receive an indeterminate number of parameters.
- We also need to indicate that our decorator function receives these parameters by adding asterisks (*) as a second argument in both the interior function and the decorator function.
Testing the Decorator Function
- After making these changes, we execute the program and observe that it performs calculations correctly for both addition and subtraction.
- We can pass any number of arguments to our decorator function, demonstrating its flexibility.
Handling Keyword Arguments
- Python allows passing keyword arguments using double asterisks (**).
- We create a new power function that takes base and exponent as keyword arguments.
- By indicating double asterisks (**) in both interior and decorator functions, we enable our decorator to handle keyword arguments as well.
Conclusion
This short video introduces us to creating decorators with parameters in Python. We have learned how to modify functions to receive arguments, create decorators that handle an indeterminate number of parameters, and extend it further to handle keyword arguments. Stay tuned for more on this topic in future videos.