Python Decorators

1. What is a Decorator?

A decorator is a special function that adds extra work to another function
without changing the original function code.

In simple words:
👉 A decorator wraps a function
👉 It adds something before or after the function runs

2. Why Do We Use Decorators?

Decorators help us:

  • Add extra features (like logging, checking, timing)

  • Keep code clean

  • Avoid repeating code

3. Simple Example (Without Decorator)

Example


 

Now suppose we want to print something before and after this function.

4. Decorator Concept (Step by Step)

Step 1: Create a Decorator Function


 

Step 2: Use Decorator on a Function


 

Output


 

5. What Does @my_decorator Mean?

This line:


 

Means:


 

👉 Python automatically wraps the function.

6. Decorator with Function Arguments

Example


 

7. Decorator Using *args and **kwargs

This makes decorator work for any function.

Example


 

8. Real-Life Example: Login Check

Example


 

9. Decorator Without @ Syntax

You can also use decorator like this:

Example


 

10. Common Beginner Mistakes

❌ Forgetting Inner Function


 

❌ Wrong – decorator must return a function.

❌ Forgetting to Call Function


 

✔ Must call:


 

11. Simple Practice Examples

Example 1: Print Lines


 

Example 2: Timing Decorator (Simple)


 

12. Summary (Python Decorators)

✔ Decorators add extra work to functions
✔ Original function is not changed
✔ Use @decorator_name
✔ Wrapper function is required
✔ Very powerful Python feature

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Lambda Functions

  • Recursion (easy)

  • Modules & Packages

  • Exception Handling

  • Mini Python Projects

Just tell me 😊

You may also like...