在主脚本中定义的全局变量不能被不同模块中定义的函数访问 [英] global variable defined in main script can't be accessed by a function defined in a different module
问题描述
我想在我的主python脚本中定义一些变量,并将它们用在一个单独的模块中定义的函数中。这是一个示例代码。假设主脚本命名为main.py,模块名为mod.py。
$ b
Mod.py
def fun():
打印
main.py
from mod import *
global a
a = 3
fun()
现在,这段代码给我一个错误
NameError:未定义全局名称'a'
任何人都可以解释为什么会产生错误(我的意思是,一个定义为全局的变量应该可用于所有函数,对吗?)以及可能的解决方法是什么?我已经知道这两个选项,并且不想采取任何这些方法。
- 在模块中定义变量而不是主脚本。
- 将变量作为参数传递给函数。
如果还有其他选项,请提出建议。 / h1>
我不想采用上述选项,因为当前这些值是固定的为了我。但我怀疑他们可能会在将来更改(例如,数据库名称和主机IP)。所以,我想将它们作为变量存储在一个地方。以便将来编辑脚本变得容易。如果我在每个模块中定义变量,我将不得不编辑所有这些变量。
模块间共享的全局变量通常是一个坏主意。如果你需要它们(例如为了某些配置目的),你可以这样做:
global_config.py
#定义变量
a = 3
< h1> main.py
import global_config
def fun():
#use变量
print(global_config.a)
I want to define a few variables in my main python script and use them in a function which is defined in a separate module. Here is an example code. Lets say the main script is named main.py and the module is called mod.py.
Mod.py
def fun():
print a
main.py
from mod import *
global a
a=3
fun()
Now, this code gives me an error
NameError: global name 'a' is not defined
Can anyone please explain why the error is generated (i mean, a variable defined as global should be available to all functions, right?) and what may be a work-around? I already know about these two options and don't want to take any of these
- Define the variable in the module instead of the main script.
- pass the variable as argument to the function.
If there is any other option, please suggest.
Edit
I dont want to take the above options because
- currently these values are fixed for me. But I suspect they may change in future (for example, database name and host ip). So, I want to store them as variables in one place. So that it becomes easy to edit the script in future. If I define the variables in each module, I will have to edit all of them.
- I don't want to pass them in the functions because there are too many of them, some 50 or so. I know I can pass them as **kwarg, but that doesn't look too nice.
Global variables shared among modules are generally a bad idea. If you need them though (for example for some configuration purposes), you can do it like this:
global_config.py
# define the variable
a = 3
main.py
import global_config
def fun():
# use the variable
print(global_config.a)
这篇关于在主脚本中定义的全局变量不能被不同模块中定义的函数访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!