🟡 Advanced Python · Lesson 21
Python Decorators
Python Decorators क्या है?
Python Decorators ka matlab hai: A decorator adds extra behavior to a function without changing the original function code. Simple words me, ye topic practical Python programs likhne me direct use hota hai.
Is topic ko sirf definition ke liye nahi, balki adding logging or timing jaise real examples ke liye practice karein.
यह क्यों सीखना जरूरी है?
- Ye adding logging or timing me kaam aata hai.
- Ye checking permissions se bhi connected hai.
- Isse aap code ka output aur errors better samajh paate hain.
Important Terms
| Term | Meaning |
|---|---|
| wrapper | Inner function used by a decorator to add extra behavior. |
| higher-order function | Function that accepts another function or returns a function. |
| @decorator | Syntax used to apply a decorator above a function. |
| logging | logging is an important term in this topic. |
| reuse | Using a saved model again without retraining. |
Syntax / Basic Pattern
Basic idea: pehle data तैयार करें, phir Python logic apply करें, aur finally result display करें.
Basic Pattern
def simple_logger(func):
def wrapper():
print("Function started")
func()
print("Function ended")
return wrapper
@simple_logger
def greet():Complete Example Program
Python – decorators.py
def simple_logger(func):
def wrapper():
print("Function started")
func()
print("Function ended")
return wrapper
@simple_logger
def greet():
print("Hello Python")
greet()Expected Output
Function started
Hello Python
Function ended
Program Explanation
def simple_logger(func):creates a reusable function.def wrapper():creates a reusable function.print("Function started")displays information or calculated result on the screen.func()performs the next step of the program logic.print("Function ended")displays information or calculated result on the screen.return wrappersends a result back from the function.@simple_loggerperforms the next step of the program logic.
Practical Uses
- Adding logging or timing.
- Checking permissions.
- Reusing extra behaviour.
Common Mistakes
- Making code complex when a simple function or class is enough.
- Not handling possible errors or edge cases.
- Mixing project dependencies instead of using a virtual environment.
Practice Tasks
- Program ko
decorators.pyfile me type karke run karein. - Values change karke output compare karein.
- adding logging or timing par ek छोटा example banayen.
- Logic ko apne words me 5 lines me likhein.
सारांश
Decorators in Python ko tab complete maanenge jab aap iska meaning, example, output aur practical use clearly explain kar saken.
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.