1️⃣ Function Decorators
Python me decorator ek function hota hai jo kisi dusre function ke behavior ko modify karta hai bina uske code ko directly change kiye.
Ye @ symbol ke saath use hota hai.
def greet_decorator(func):
def wrapper():
print("👋 Hello!")
func()
print("🎉 Goodbye!")
return wrapper
@greet_decorator
def say_name():
print("Mera naam AIkiPadhai hai!")
say_name()
👉 Output:
👋 Hello!
Mera naam AIkiPadhai hai!
🎉 Goodbye!
---
2️⃣ Decorator with Arguments
Kabhi kabhi function me arguments hote hain — decorator ko unhe handle karna hota hai using *args aur **kwargs.
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Function '{func.__name__}' called with {args} {kwargs}")
result = func(*args, **kwargs)
print(f"Result: {result}")
return result
return wrapper
@log_decorator
def add(a, b):
return a + b
add(5, 10)
---
3️⃣ Chaining Multiple Decorators
Multiple decorators ek function par lagaye ja sakte hain. Ye upar se neeche tak apply hote hain (top-down order me).
def star(func):
def wrapper():
print("⭐" * 10)
func()
print("⭐" * 10)
return wrapper
def smile(func):
def wrapper():
print("😊")
func()
print("😊")
return wrapper
@star
@smile
def greet():
print("Namaste!")
greet()
---
4️⃣ Class Decorators
Class decorators tab use karte hain jab aap kisi class ke behavior ko modify karna chahte ho.
def add_method(cls):
cls.greet = lambda self: print("Hello from", self.__class__.__name__)
return cls
@add_method
class Student:
pass
s = Student()
s.greet()
---
5️⃣ Context Managers (with Statement)
Context managers resource management ke liye hote hain — jaise file handle, network connection, ya database.
with statement ensure karta hai ki resource safely open aur close ho.
with open("data.txt", "w") as f:
f.write("AIkiPadhai Rocks!")
# file automatically closed yahan
---
6️⃣ Custom Context Manager
Apna khud ka context manager banana easy hai using __enter__() aur __exit__().
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
print("Opening file...")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
print("Closing file...")
self.file.close()
with FileManager("sample.txt", "w") as f:
f.write("Hello from context manager!")
---
7️⃣ contextlib Module
contextlib decorator ke saath ek function ko context manager bana sakte hain — short aur clean syntax me.
from contextlib import contextmanager
@contextmanager
def simple_manager():
print("Enter...")
yield
print("Exit...")
with simple_manager():
print("Working inside block...")
👉 Output:
Enter...
Working inside block...
Exit...
---
💡 Summary
- Decorators functions ke behavior ko enhance karte hain without touching original code.
- Multiple decorators ko chain kar sakte ho.
- Context managers resources ko safely handle karte hain.
contextlibse short aur readable managers bana sakte ho.