Decorators
Python decorators are a powerful and versatile feature used for modifying or enhancing the behavior of functions or methods without changing their source code. They are often used for tasks like logging, authentication, and memoization. Here's an explanation of decorators with examples:
1. Basics of Decorators:
In Python, decorators are functions that take another function as an argument and return a new function that usually extends or modifies the behavior of the input function. Decorators are commonly denoted using the "@" symbol in Python
2. Creating a Simple Decorator:
Here's a simple decorator that logs the execution of a function:
def log_function_execution(func):
When you call `say_hello`, it gets wrapped by the `log_function_execution` decorator, and additional logging is performed before and after the `say_hello` function is executed.
3. Decorating Functions with Arguments:
You can also create decorators that accept arguments. Here's an example:
In this example, the `repeat_n_times` decorator takes an argument `n`, and you can apply it to functions with different repeat counts.
4. Class-Based Decorators:
Decorators can also be implemented as classes. Here's an example:
In this example, the `TimerDecorator`
class is used as a decorator to measure the execution time of the `slow_function`
.
5. Built-in Decorators:
Python also has several built-in decorators like `@staticmethod
`, `@classmethod
`, and `@property
`. These decorators provide special behavior to methods in classes.
Decorators are a powerful tool for enhancing the functionality and behavior of Python functions and methods while keeping the code clean and maintainable. Understanding decorators is crucial for more advanced Python programming and building clean and reusable code.
Last updated