Python Decorators
1. What is a Decorator?
A decorator is a function that adds extra work to another function.
In simple words:
👉 A decorator wraps a function
👉 It runs before or after the function
👉 It does not change the original function code
2. Real-Life Example
Think of a gift box 🎁
-
Gift = function
-
Wrapper paper = decorator
Decorator adds something extra around the function.
3. Why Use Decorators?
Decorators help us to:
✔ Add logging
✔ Add security (login check)
✔ Measure time
✔ Reuse code
4. Function Without Decorator
Example
5. Simple Decorator Example
Step 1: Create Decorator
Step 2: Use Decorator
Output:
6. How @ Works?
This is same as:
7. Decorator with Arguments
Example
8. Decorator with Multiple Arguments
Example
9. Real Use Example (Login Check)
Example
10. Using functools.wraps (Good Practice)
This keeps function name and info.
Example
11. Common Beginner Mistakes
❌ Forgetting to Call Function Inside Wrapper
✔ Correct:
❌ Not Returning Wrapper
❌ Wrong.
12. Simple Practice Examples
Example 1: Time Logger
Example 2: Math Decorator
Example 3: Decorator Without @
13. Summary (Python Decorators)
✔ Decorators add extra behavior
✔ Use @decorator_name
✔ Wrapper function is important
✔ Supports arguments
✔ Very powerful Python feature
📘 Perfect for Beginner & Advanced eBook
This chapter is ideal for:
-
Python learners
-
Interview preparation
-
Real-world projects
-
Clean code writing
If you want next, I can write:
-
Advanced Decorators
-
Class Decorators
-
Generators vs Decorators
-
Real Python Projects
Just tell me 😊
