简体   繁体   English

Python 3:跨模块的全局变量的可见性

[英]Python 3: The visibility of global variables across modules

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. 假设您有2个模块,其中一个模块具有要在另一个模块中读取的全局变量。 Is there a way to make these accessible across modules without having to refer to them as module.variable each time? 有没有一种方法可以使它们跨模块访问而不必每次都将它们称为module.variable?

Example: 例:

modulea.py: 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: 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. 建议通过使用“ from module import *”来复制而不是引用全局变量。

Thanks in advance for any help. 在此先感谢您的帮助。

from module import * binds the objects in module to like named variables in the current module. from module import *绑定的对象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. 对于intstr等不可变对象,这将重新绑定变量,并且现在两个模块具有不同的值。

If you want to make sure you always reference the same object, keep the namespace reference. 如果要确保始终引用相同的对象,请保留名称空间引用。

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

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