Decorators are a powerful feature in Python that allow you to modify or extend the behavior of functions or methods without changing their actual code. They are functions that wrap another function to enhance or alter its functionality.
Examples
[pastacode lang=”markup” manual=”def%20my_decorator(func)%3A%0A%20%20%20%20def%20wrapper()%3A%0A%20%20%20%20%20%20%20%20print(%22Decorated%22)%20%20%20%0A%20%20%20%20return%20wrapper%0A%0A%40my_decorator%0Adef%20say_hello()%3A%0A%20%20%20%20print(%22Hello!%22)%0A%0Asay_hello()%0A” message=”” highlight=”” provider=”manual”/]Output
[pastacode lang=”python” manual=”Decorated%0AHello!%0A” message=”” highlight=”” provider=”manual”/]Features
- Decorators wrap a function
- Allows code reusability
- Decorators are higher-order functions
Advantages
- Keeps code cleaner and more readable
- Helps in separating the logic of modifying behavior
- Enhances code reuse by allowing common functionality
 Uses
- Used to automatic logging function.
- To measures the execution time of functions
- Used to Cache the results of expensive function calls to improve performance.
Â