Python Decorators
In this page:
def decorator_name(func):
def wrapper(*args, **kwargs):
# before
result = func(*args, **kwargs)
# after
return result
return wrapper
@decorator_name
def function_name():
pass
Decorator क्या है?
Decorator एक function है जो दूसरे function को लपेटता है, original के permanently code को बदले बिना उसके चलने से पहले या बाद में behavior जोड़ता है -- यह एक function अंदर लेता है और (आमतौर पर नया, wrapped) function बाहर लौटाता है।
उदाहरण: What is a Decorator?
def shout(func):
def wrapper():
print(func().upper()) # extra behavior added around the original call
return wrapper
@shout
def greet():
return "hello"
greet() # actually calls wrapper(), not the original greet
एक Basic Decorator डिज़ाइन करना
किसी decorator को manually apply करने का मतलब बस उसे अपने target function के साथ call करना और वह जो भी लौटाए उसे इस्तेमाल करना है: 'wrapped = my_decorator(original_function)' -- इस manual रूप को समझना ही @ shorthand के असली व्यवहार को स्पष्ट बनाता है, जादू जैसा महसूस होने की बजाय।
उदाहरण: Designing a Basic Decorator
def shout(func):
def wrapper():
print(func().upper())
return wrapper
def greet():
return "hello"
wrapped = shout(greet) # manually applying the decorator, same as @shout
wrapped()
Arguments के साथ Decorate करना
चूँकि decorate किया जा रहा function arguments का कोई भी combination स्वीकार कर सकता है, एक general-purpose wrapper उन्हें *args और **kwargs से collect करके बिना बदले original function को forward कर देता है -- इसके बिना, कोई decorator सिर्फ़ एक exact, fixed signature वाले functions पर ही काम करेगा।
उदाहरण: Decorating with Arguments
def log(func):
def wrapper(*args, **kwargs): # accepts any arguments the original function takes
print("Calling", func.__name__)
return func(*args, **kwargs) # forwards them unchanged
return wrapper
@log
def add(a, b):
return a + b
print(add(2, 3))
@ Syntax
किसी function definition के ठीक ऊपर '@my_decorator' लिखना बिल्कुल उसके बाद 'my_function = my_decorator(my_function)' लिखने के बराबर है -- @ syntax सिर्फ़ सुविधा है, नीचे कोई अलग mechanism नहीं।
उदाहरण: The @ Syntax
def shout(func):
def wrapper():
return func().upper()
return wrapper
@shout
def greet():
return "hi"
print(greet()) # same as greet = shout(greet)
Multiple Decorators
एक function पर कई decorators stack करना उन्हें नीचे से ऊपर apply करता है -- function के सबसे करीब वाला decorator उसे पहले लपेटता है, और उसके ऊपर हर decorator नीचे वाले के result को लपेटता है, इसलिए जब decorators interact करते हैं तो execution order मायने रखता है।
उदाहरण: Multiple Decorators
def bold(func):
def wrapper():
return "**" + func() + "**"
return wrapper
def shout(func):
def wrapper():
return func().upper()
return wrapper
@bold
@shout # applied first, closest to the function
def greet():
return "hi"
print(greet())
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: