简体   繁体   中英

How do I update a global variable in python?

I am declaring global variable in sample1.py like this and updating

sample1.py
var = 0
def foo():
    global var
    var = 10

In sample2.py I am importing this global variable

sample2.py
from sample1 import var

def foo1():
    print var

but, still it is printing "0" instead of "10". If print it in sample1.py it is printing "10".

What went wrong?

What is wrong is that the function from sample1.py is never called, ergo you variable is never initialized with 10

Correct way

Sample1.py

var = 0
def Function1:
   var = 10

Sample2.py

import Sample1
Sample1.Function1()
print(Function1.var)

Because you didn't called the function foo() in sample2.py , right now only declared the variable with 0 when you call the function foo() , then only it will update.

update sample2.py like this,

from sample1 import var,foo
foo()

def foo1():
    print var

Actually, even though you have already called function foo , it won't work. Because when you use from sample1 import var , you just get a copy of sample1.var , but not really get the pointer of it. So it won't be updated when sample1.var is updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM