Python全局范围的麻烦 [英] Python global scope troubles

查看:73
本文介绍了Python全局范围的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在Python中修改不同文件之间的全局变量.例如:

I'm having trouble modifying global variables between different files in Python. For example:

File1.py:

x = 5

File2.py:

from File1 import *

def updateX():
    global x
    x += 1

main.py:

from File2 import * 

updateX()
print x #prints 5

推荐答案

这里要注意几件重要的事情.

There are several important things to note here.

首先,global不是全局的.真正的全局事物(如内置函数)存储在__builtin__模块或Python 3中的builtins中.global表示模块级.

First, global isn't global. The really global things, like built-in functions, are stored in the __builtin__ module, or builtins in Python 3. global means module-level.

第二,当您使用import *时,将获得与import *所使用的模块中的名称相同的名称的新变量,它们引用相同的对象.这意味着如果您随后在一个模块中重新分配变量,则另一个模块将看不到更改.另一方面,使可变对象可变是两个模块都看到的变化.

Second, when you import *, you get new variables with the same names as the ones in the module you import *'d from, referring to the same objects. That means if you then reassign the variable in one module, the other doesn't see the change. On the other hand, mutating a mutable object is a change both modules see.

这意味着在main.py的第一行之后:

This means that after the first line of main.py:

from File2 import *

File1File2__main__(运行主脚本的模块)都具有引用同一个5对象的单独的x变量. File2__main__也具有引用updateX函数的updateX变量.

File1, File2, and __main__ (the module the main script runs in) all have separate x variables referring to the same 5 object. File2 and __main__ also have updateX variables referring to the updateX function.

第二行之后:

updateX()

仅将File2x变量重新分配给6. (该函数记录了它的定义位置,因此它更新了File2x而不是__main__的.)

Only File2's x variable is reassigned to 6. (The function has a record of where it was defined, so it updates File2's x instead of __main__'s.)

第三行:

print x

打印__main__x,仍然是5.

这篇关于Python全局范围的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆