在文件之间使用全局变量? [英] Using global variables between files?
问题描述
我对全局变量的工作方式有点困惑.我有一个大项目,大约有 50 个文件,我需要为所有这些文件定义全局变量.
I'm bit confused about how the global variables work. I have a large project, with around 50 files, and I need to define global variables for all those files.
我所做的是在我的项目 main.py
文件中定义它们,如下所示:
What I did was define them in my projects main.py
file, as following:
# ../myproject/main.py
# Define global myList
global myList
myList = []
# Imports
import subfile
# Do something
subfile.stuff()
print(myList[0])
我试图在 subfile.py
中使用 myList
,如下
I'm trying to use myList
in subfile.py
, as following
# ../myproject/subfile.py
# Save "hey" into myList
def stuff():
globals()["myList"].append("hey")
我尝试过的另一种方法,但也没有用
# ../myproject/main.py
# Import globfile
import globfile
# Save myList into globfile
globfile.myList = []
# Import subfile
import subfile
# Do something
subfile.stuff()
print(globfile.myList[0])
在 subfile.py
里面我有这个:
# ../myproject/subfile.py
# Import globfile
import globfile
# Save "hey" into myList
def stuff():
globfile.myList.append("hey")
但同样,它没有用.我应该如何实施?我知道它不能那样工作,当两个文件并不真正相互了解时(以及子文件不知道主文件),但我想不出如何做到这一点,而不使用 io 写作或泡菜,这我不想做.
But again, it didn't work. How should I implement this? I understand that it cannot work like that, when the two files don't really know each other (well subfile doesn't know main), but I can't think of how to do it, without using io writing or pickle, which I don't want to do.
推荐答案
问题是你从 main.py
定义了 myList
,但是 subfile.py
需要使用它.这里有一个干净的方法来解决这个问题:将所有全局变量移动到一个文件中,我称这个文件为 settings.py
.这个文件负责定义全局变量并初始化它们:
The problem is you defined myList
from main.py
, but subfile.py
needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py
. This file is responsible for defining globals and initializing them:
# settings.py
def init():
global myList
myList = []
接下来,您的 subfile
可以导入全局变量:
Next, your subfile
can import globals:
# subfile.py
import settings
def stuff():
settings.myList.append('hey')
请注意,subfile
不会调用 init()
——该任务属于 main.py
:
Note that subfile
does not call init()
— that task belongs to main.py
:
# main.py
import settings
import subfile
settings.init() # Call only once
subfile.stuff() # Do stuff with global var
print settings.myList[0] # Check the result
通过这种方式,您可以实现目标,同时避免多次初始化全局变量.
This way, you achieve your objective while avoid initializing global variables more than once.
这篇关于在文件之间使用全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!