Why in the last print x = 2?
def func_outer(): x = 2 print('x равно', x) def func_inner(): global x x = 5 print (x) func_inner() print('Локальное x сменилось на', x) func_outer()
Why in the last print x = 2?
def func_outer(): x = 2 print('x равно', x) def func_inner(): global x x = 5 print (x) func_inner() print('Локальное x сменилось на', x) func_outer()
For example, you have two functions, one of which is nested in the second. If you want to get the value of a variable from the first function in the second function, then in the second function you need to specify nonlocal to the variable that you want to pass. x (1) is the first function, x (2). Suppose that we have x (1) equal to 5. We specified nonlocal x (2), so x (1) will be equal to 5 in the second function until we rewrite this variable. It will be the same if we create another nested function to which we also want to pass this variable.
def func_outer(): x = 2 print('x равно', x) def func_inner(): nonlocal x print (x) x = 5 print (x) def func_three(): nonlocal x print ('До изменения третьей', x) x = 9 print('Чекаю третью после изменения', x) func_three() func_inner() print('Локальное x сменилось на', x) func_outer()
As for global. There is a similar situation. But in this case we can transfer to a function or class, the value of a variable outside the body of a class or function.
global x x = 2 def func_outer(): #x = 2 print('x равно', x) def func_inner(x): #nonlocal x print (x) x = 5 print (x) def func_three(x): #nonlocal x print ('До изменения третьей', x) x = 9 print('Чекаю третью после изменения', x) func_three(x) func_inner(x) print('Локальное x сменилось на', x) func_outer()
global
not used outside functions. To use it in the methods, it seems to me, is also such an idea. - Sour Sourseglobals()
in the function namespace, and use it. Eliminates the name conflict situation. - Sour Sourse 5:28 pmSource: https://ru.stackoverflow.com/questions/975098/
All Articles
global x
->nonlocal x
:) - gil9red