简体   繁体   English

Python 导入和全局变量

[英]Python Import and Global Variables

Suppose I have a file:假设我有一个文件:

# main.py

import foo

my_global = "global variable"
foo.print_global()

and another:另一个:

# foo.py

def print_global():
    global my_global
    print(my_global)

Why do I get NameError: name 'my_global' is not defined when I run main.py please?当我运行main.py时,为什么会出现NameError: name 'my_global' is not defined How can I make my_global available to foo.py ?如何使my_global可用于foo.py Is it a bad idea to try - maybe I should always pass values as function arguments in this kind of situation?尝试是不是一个坏主意 - 也许在这种情况下我应该总是将值作为函数参数传递?

Python doesn't have process-wide globals, only module-level globals. Python 没有进程范围的全局变量,只有模块级的全局变量。 foo.print_global looks at foo.my_global , not main.my_global , which is what you set. foo.print_globalfoo.my_global ,而不是main.my_global ,这是你设置的。 That is, the scope that print_global uses for global variables is determined when print_global is defined , not when it is called .也就是说, print_global用于全局变量的范围是在定义print_global确定的,而不是在调用它时确定。

This would do what you expect.这会做你所期望的。

import foo

foo.my_global = "global variable"
foo.print_global()

Note that foo.py should not rely on someone else creating its global variable(s) before calling print_global ;请注意,在调用print_global之前, foo.py不应依赖其他人创建其全局变量; at the very least, foo.py should initialize my_global to None , if not some other default value.至少, foo.py应该将my_global初始化为None ,如果不是其他一些默认值。

Also note that the solution above is not the same as还要注意的是上面的解决方案是一样的

from foo import my_global

my_global = "..."

This creates a new global name in the current module, which is initialized using the current value of foo.my_global .这造成当前模块,这是使用的当前值初始化一个新的全局名称foo.my_global The subsequent assignment changes the name of the "local" global variable, not foo.my_global .随后的赋值更改了“本地”全局变量的名称,而不是foo.my_global

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

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