What are Python Decorators?
A decorator is a function that takes another function as an argument and extends its behavior without modifying its source code. It's an elegant way to apply cross-cutting concerns like logging, timing, and access control.
python
Creating Complex Decorators: Handling Arguments
The
*args and **kwargs ensure that the decorator can handle any number of positional and keyword arguments passed to the wrapped function.python
Built-in Decorators
Python comes with several useful decorators for specialized tasks.
1. @property
This turns a class method into a "getter" that you can access like a normal attribute. You can also define "setter" and "deleter" methods.
python
2. @staticmethod & @classmethod
- @staticmethod: Defines a method that doesn't need access to
selforcls. It's just a regular function that lives inside a class. - @classmethod: Recieves the class itself (
cls) as the first argument instead ofself. Useful for factory methods (creating new objects differently).
python
Why Use Decorators?
- Don't Repeat Yourself (DRY): Apply logic (like auth or logging) in one place.
- Clean Code: Keep the core logic of your functions separate from utility logic.
- Readability: Makes the programmer's intent very clear as soon as they read the
@decorator.
Summary
| Feature | Syntax | Purpose |
|---|---|---|
| Decorator | @my_decorator | Extend function behavior |
| Property | @property | Data encapsulation / getters |
| StaticMethod | @staticmethod | Utility function in class |
| ClassMethod | @classmethod | Factory / class-level logic |
| Wrapper | functools.wraps | Preverses function metadata |
| Best For | Logging, Timing, Auth, Cache |