简体   繁体   中英

Python global variable is not working as expected

I'm just starting out with Python and experimenting with different solutions. I was working with global variables and I ran into something but don't know why it's doing what it's doing.

To start, I have two modules: test1 and test2. test1 is as follows:

import test2
num = 0
def start():
    global num
    num = num + 5
    print 'Starting:'
    print num
    test2.add()
    print 'Step 1:'
    print num
    test2.add()
    print 'Step 2:'
    print num

And test2 is this:

import test1
def add():
    test1.num = test1.num + 20

When I run test1.start() the output is:

Starting:
5
Step 1:
25
Step 2:
45

Why doesn't test2 need the global declaration to modify the variable in test1? Line 5 in test1 requires it at line 4, but if I remove both it still works (0, 20,40). I'm just trying to figure out why it's not working as I expected it to.

Thanks.

The global declaration is not for modifying the name, it's for rebinding it. Since you are accessing the name via its module what you are doing is modifying the module .

From test2's perspective, test1.num is a variable belonging to the module test1.

The global keyword only specifics that the scoping for that variable is module-level (ie not local).

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