Python में Closures
In this page:
def outer(outer_variable):
def inner():
return outer_variable
return inner
closure = outer(value)
Closure क्या है?
Closure एक ऐसा function है जो उस scope के variables को "याद" रखता है जिसमें वह define हुआ था, भले ही वह outer function पहले ही खत्म हो चुका हो और अन्यथा उन्हें discard कर चुका होता।
उदाहरण: What is a Closure?
def outer():
message = "Hi"
def inner():
print(message) # inner "remembers" message even after outer returns
return inner
closure = outer()
closure() # message is still accessible here
Outer State को बचाए रखना
क्योंकि closure अपने enclosing scope से specific values को lock कर लेता है, आप उसका इस्तेमाल मांग पर specialized helper functions generate करने के लिए कर सकते हैं -- जैसे कोई make_multiplier(3) जो एक ऐसा function return करता है जो हमेशा 3 से multiply करता है, बिना हर जगह उस 3 को hardcode किए।
उदाहरण: Preserving Outer State
def make_multiplier(factor):
def multiplier(x):
return x * factor # factor is captured from the enclosing call
return multiplier
times3 = make_multiplier(3) # locks in factor=3
print(times3(10))
Closures का Inspection
हर closure एक __closure__ attribute expose करता है जिसमें "cell" objects होते हैं जो उन exact variables को reference रखते हैं जिन्हें उसने capture किया था, यही वह तरीका है जिससे Python उन values को enclosing function के return होने के बाद भी alive रखता है।
उदाहरण: Inspecting Closures
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
times3 = make_multiplier(3)
print(times3.__closure__[0].cell_contents) # inspects the captured factor value directly
Dynamic State Modifications
nonlocal keyword किसी closure को अपने enclosing scope से capture किए गए variable को सिर्फ़ पढ़ने ही नहीं बल्कि असल में modify करने भी देता है, यही तरीका है जिससे आप सिर्फ़ nested functions इस्तेमाल करके, किसी class के बिना, एक simple counter या accumulator बना सकते हैं।
उदाहरण: Dynamic State Modifications
def make_counter():
count = 0
def counter():
nonlocal count # allows modifying the captured count variable
count += 1
return count
return counter
counter = make_counter()
print(counter()) # 1
print(counter()) # 2, count persists between calls
Closures कब इस्तेमाल करें
जब आपको सिर्फ़ थोड़े से याद रखे गए state के साथ एक छोटा-सा behavior bundle करना हो तो closures पूरी एक class define करने का एक हल्का विकल्प हैं -- जैसे ही उस state को share करने वाले कई related methods चाहिए हों, class की तरफ़ बढ़ें।
उदाहरण: When to Use Closures
def make_counter(): # closure: one small behavior + state
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
# A class would be overkill here for just one counter method
c = make_counter()
print(c(), c())
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: