Accessing a variable from a binary function in Python

The following code:

x = 0 print "Initialization: ", x def f1(): x = 1 print "In f1 before f2:", x def f2(): global x x = 2 print "In f2: ", x f2() print "In f1 after f2: ", x f1() print "Final: ", x 

prints:

 Initialization: 0 In f1 before f2: 1 In f2: 2 In f1 after f2: 1 Final: 2 

Is there a way for f2 access f1 variables?

+4
source share
3 answers

You can access variables, the problem is in the task. In Python 2, there is no way to restore x new value. See PEP 227 (nested areas) for details.

In Python 3, you can use the new nonlocal keyword instead of global . See PEP 3104 .

+5
source

In Python 3, you can define x as nonlocal in f2.

In Python 2, you cannot directly assign f1 x to f2. However, you can read its value and gain access to your members. So this could be a workaround:

 def f1(): x = [1] def f2(): x[0] = 2 f2() print x[0] f1() 
+5
source

delete the global statement:

 >>> x 0 >>> def f1(): x = 1 print(x) def f2(): print(x) f2() print(x) >>> f1() 1 1 1 

if you want to change the variable x from f1 , then you need to use the global statement in each function.

0
source

Source: https://habr.com/ru/post/1301727/


All Articles