Python 3:跨模块的全局变量的可见性 [英] Python 3: The visibility of global variables across modules
问题描述
之前已经提出过类似的问题:
假设您有2个模块,其中一个具有全局变量,您想从另一个模块中读取它们。有没有一种方法可以让这些模块可以跨模块访问,而无需每次都将它们作为module.variable引用?
示例:
modulea.py:
import moduleb
from moduleb import *
print(A String:+ astring)
print(Module B:+ moduleb.astring)
afunction()
print(A String:+ astring)
print(Module B:+ moduleb.astring)
moduleb.py:
astring =dlroW olleH
def afunction():
全局astring
astring =Hello World
输出为
字符串:dlroW olleH
模块B:dlroW olleH
字符串:dlroW olleH
模块B:Hello World
表明通过使用from module import *,全局变量被复制而不是被引用。
预先感谢您提供任何帮助。
来自模块导入* 将 module
中的对象绑定为命名变量在当前模块中。这不是副本,而是添加对同一对象的引用。两个模块都会看到相同的对象,直到其中一个重新绑定对象。修改可变对象不会重新绑定变量,因此可以添加到列表等操作。但重新分配变量确实会重新指定它。通常情况下,重新绑定很简单:
myvar = something_else
但有时它并不那么清楚b
$ b
myvar + = 1
对于不可变对象,如 int
或 str
,这将重新绑定变量,现在这两个模块具有不同的值。
如果您想确保始终引用相同对象,保留名称空间引用。
Similar questions have been asked before:
here, here and here, and I am aware of these.
Say you have 2 modules where one has global variables that you want to read from in another module. Is there a way to make these accessible across modules without having to refer to them as module.variable each time?
Example:
modulea.py:
import moduleb
from moduleb import *
print("A String: " + astring)
print("Module B: " + moduleb.astring)
afunction()
print("A String: " + astring)
print("Module B: " + moduleb.astring)
moduleb.py:
astring = "dlroW olleH"
def afunction():
global astring
astring = "Hello World"
The output is
A String: dlroW olleH
Module B: dlroW olleH
A String: dlroW olleH
Module B: Hello World
suggesting that by using "from module import * " the global variables are copied rather than referenced.
Thanks in advance for any help.
from module import *
binds the objects in module
to like named variables in the current module. This is not a copy, but the addition of a reference to the same object. Both modules will see the same object until one of them rebinds the object. Modifying a mutable object doesn't rebind the variable so an action such as appending to a list is okay. But reassigning the the variable does rebind it. Usually the rebind is straight forward:
myvar = something_else
But sometimes its not so clear
myvar += 1
For immutable objects such as int
or str
, this rebinds the variable and now the two modules have different values.
If you want to make sure you always reference the same object, keep the namespace reference.
这篇关于Python 3:跨模块的全局变量的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!