简体   繁体   中英

modify a global variable among two files in python

I have two python files: first test2.py :

a = 1


def func1():
    global a
    print(id(a))
    a += 1

then test1.py

from test2 import a, func1

def func0():
    global a
    print(id(a))
    a += 1

func0()

func1()

print(a)

It turns out if I run test1.py , the result is 2 rather than 3 which I thought it should be. I check the id of a in two functions and they are the same.

I have invoked two functions func0 and func1 , why global variable just did the addition once?

First, don't use global variables. Second, both modules test1 and test2 have separate namespaces. Use explicit reference to module test2 .

import test2
from test2 import func1

def func0():
    print(id(test2.a))
    test2.a += 1

func0()

func1()

print(test2.a)

The global keyword makes it global to your current module, in your case test1 and test2 . When doing the import it's effectively copying the value to your local module scope.

Perhaps this makes it clearer because that's effectively what happens:

import test2

a = test2.a
a = 123
# what is the value of test2.a? Unchanged, only the local a was changed

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