简体   繁体   English

NameError:全局名称未使用另一个 .py 文件中定义的全局变量定义

[英]NameError: global name is not defined with a global variable defined in another .py file

My code looks like this:我的代码如下所示:

config.py配置文件

global var
var = None

file1.py文件1.py

from config import *

def foo1():
   global var
   var = <object>

def foo2():
   var.doWork1()  # this works

file2.py文件2.py

from config import *

def foo3():
   var.doWork2() # this throws global name 'var' is not defined

Why am I not able to access var in the second module?为什么我无法访问第二个模块中的 var?

The solution was not to use global.解决方案是不使用全局。

Instead of doing而不是做

from config import *

I replaced it with我用

import config

And then accessed var via config.var然后通过 config.var 访问 var

This worked.这奏效了。

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

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