Python में Scope और Lifetime
In this page:
global_variable = value
def function_name():
local_variable = value
global global_variable
Local Scope
किसी function के अंदर बनाया गया variable सिर्फ़ उस function के local scope में exist करता है -- यह function शुरू होने पर बनता है और return होने पर destroy हो जाता है, उस function के बाहर किसी भी code को दिखाई नहीं देता।
उदाहरण: Local Scope
def greet():
message = "Hello" # local variable, only exists inside greet()
print(message)
greet()
Global Scope
किसी script के top level पर, किसी function के बाहर assign किए गए variables global scope में रहते हैं और किसी भी function के अंदर से बिना किसी special syntax के *पढ़े* जा सकते हैं -- सिर्फ़ उन्हें *दोबारा assign* करने के लिए extra steps चाहिए।
उदाहरण: Global Scope
count = 10 # global variable, defined outside any function
def show():
print(count) # can read the global variable without any special syntax
show()
global Keyword
किसी function के अंदर किसी global variable के नाम पर assign करने की कोशिश करना आमतौर पर outer variable को छूने के बजाय एक नया local variable बना देता है; इसे पहले global keyword से declare करना Python को बताता है कि आप असली outer variable को modify करना चाहते हैं।
उदाहरण: The global Keyword
count = 0
def increment():
global count # declares intent to modify the outer count, not create a local one
count += 1
increment()
print(count)
Nonlocal Scope
किसी function के अंदर nested किसी दूसरे function में, nonlocal inner function को enclosing (लेकिन global नहीं) function के scope के किसी variable को modify करने देता है -- यह global से अलग है, जो सीधे module level तक पहुँचता है।
उदाहरण: Nonlocal Scope
def outer():
value = 1
def inner():
nonlocal value # refers to outer's value, not the global scope
value += 1
inner()
print(value)
outer()
Built-in Scope
print(), len(), और int() जैसे built-in names Python के built-in scope में रहते हैं, जो सबसे बाहरी layer है और सबसे आख़िर में जाँचा जाता है, यही वजह है कि आप इन्हें बिना import या खुद define किए, कहीं से भी call कर सकते हैं।
उदाहरण: Built-in Scope
print(len("hello"))
print(int("42"))
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: