Decorator in Python
Decorator in Python
A decorator in Python is a function that modifies the behavior of another function — without changing its actual code.
You can think of decorators as wrappers around functions: they let you add extra functionality before or after a function runs.
📌 Why Use Decorators?
-
Logging
-
Timing function execution
-
Access control
-
Code reuse
-
Input validation
✅ Basic Syntax
✅ Simple Example of a Decorator
🔹 Step 1: Define a Decorator Function
🔹 Step 2: Apply the Decorator
Output:
✅ Example with Arguments
Output:
✅ Real-Life Use: Timing a Function
✅ Summary
Term | Meaning |
---|---|
@decorator_name | Syntax to apply a decorator |
wrapper() | Inner function that adds extra code |
*args, **kwargs | To allow any number of arguments |
Comments
Post a Comment