पाठ 38 / 49
डेकोरेटर की मूल बातें
@ syntax और *args के साथ decorators से functions का code बदले बिना उनमें behaviour जोड़ें।
@decorator सिंटैक्स
डेकोरेटर एक फ़ंक्शन लेता है और एक नया लपेटा हुआ फ़ंक्शन लौटाता है। def के ऊपर @decorator, func = decorator(func) का संक्षिप्त रूप है।
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@shout
def greet(name):
return f"hello, {name}"
print(greet("ada")) # HELLO, ADAबदलना नहीं, लपेटना
डेकोरेटर गिफ्ट रैपिंग जैसा है — अंदर का फ़ंक्शन वही रहता है, पर अब उसके चारों ओर अतिरिक्त व्यवहार आ जाता है।