Python 3:跨模块的全局变量的可见性 [英] Python 3: The visibility of global variables across modules

查看:847
本文介绍了Python 3:跨模块的全局变量的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前已经提出过类似的问题:

此处此处,我知道这些。



假设您有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屋!

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