Please tell me how does "nonlocal" work in Python?
Closed due to the fact that the issue is too general for the participants Sergey Gornostaev , Xander , Dmitry Kozlov , 0xdb , Air 19 Mar at 2:59 .
Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .
|
1 answer
When declaring a variable through nonlocal, it will refer to a variable with the same name in the nearest closure, excluding global variables
For example, ad without nonlocal
x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 0 And now with nonlocal, x in inner () is x in outer ()
x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 2 # global: 0 And with global will be so
x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 2 - Thank you very much everything is very clear and understandable - Alexey
- I apologize, it is a little incomprehensible how the global works - Alex
|