Decorator Practically
Decorators in Python: Concrete Examples
Basic Function Decorators
In Python, decorators are implemented using the @
symbol, followed by the decorator function name, placed above the function definition they’re decorating.
Let’s start with a simple example:
In this example, uppercase_decorator
is a function that takes another function as an argument, modifies its behavior (by converting the result to uppercase), and returns the modified function.
Function Decorators with Arguments
Decorators can also work with functions that accept arguments:
This decorator logs the name of the function being called before executing it.
Simple Class Decorator
Decorators can also be applied to classes. Here’s a simple example:
This decorator adds a greet
method to the Person
class.
Decorators with Parameters
We can create decorators that accept parameters:
This repeat
decorator takes an argument specifying how many times the decorated function should be called.
Conclusion
These examples demonstrate the basic usage of decorators in Python. They allow for modifying or enhancing the behavior of functions and classes without changing their source code. Decorators provide a clean and reusable way to extend functionality, making code more modular and easier to maintain.