SkillByAIइंटरैक्टिव संस्करण खोलें →

पाठ 21 / 49

स्कोप और क्लोज़र

LEGB scope, global व nonlocal keywords और अपना environment याद रखने वाले closures समझें।

LEGB स्कोप नियम

पायथन नामों को LEGB नियम से खोजता है: Local, Enclosing, Global, Built-in — इसी क्रम में।

global और nonlocal

global और nonlocal किसी भीतरी फ़ंक्शन को बाहरी स्कोप के वेरिएबल को बदलने देते हैं, बजाय उसे छिपाने के।

def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

counter = make_counter()
print(counter())  # 1
print(counter())  # 2

क्लोज़र क्या है?

ऊपर make_counter एक क्लोज़र है — increment, count को "क्लोज़ ओवर" करता है और कॉल के बीच अपनी निजी कॉपी ज़िंदा रखता है।