简体   繁体   English

Python全局变量未按预期工作

[英]Python global variable is not working as expected

I'm just starting out with Python and experimenting with different solutions. 我刚开始使用Python并尝试不同的解决方案。 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和test2。 test1 is as follows: test1如下:

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: 而test2是这样的:

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

When I run test1.start() the output is: 当我运行test1.start()时,输出为:

Starting: 开始:
5
Step 1: 第1步:
25 25
Step 2: 第2步:
45 45

Why doesn't test2 need the global declaration to modify the variable in test1? 为什么test2不需要全局声明来修改test1中的变量? Line 5 in test1 requires it at line 4, but if I remove both it still works (0, 20,40). test1的第5行在第4行需要它,但是如果我将两者都删除,它仍然可以工作(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. global声明不是用于修改名称,而是用于重新绑定它。 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. 从test2的角度来看,test1.num是属于模块test1的变量。

The global keyword only specifics that the scoping for that variable is module-level (ie not local). global关键字仅指定该变量的作用域是模块级别的(即不是本地的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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