我是python的新手,仍然在为noob问题学习。我目前正在开发一个跨越多个文件的程序,其中一个是“主文件”,它是唯一运行的文件。我正在尝试创建一个名为mainList的变量,使其可以在所有文件中访问。我希望它是如此,如果我在一个文件中更改它,它会在其他文件中更新。 我尝试使用全局,但它没有更新所有文件中的列表。 这是我的三个文件的一个非常简化的版本:
这是mainFile:#I only run mainFile
import file1
import file2
file2.search(mainList)
这是file1:
import file2
class Library:
#Alot of code I will not post here, but it reads data from a file and then stores
#the instances in mainList by using a for loop and then appending to the list.
#This code reads data from a text file and stores the data in every line in a
#different instance at an encapsulated field called data, the instances are stored
#the mainList.
这是file2:
import file1
global mainList
mainList = []
#Alot of code I will not post here for simplicity sake
def search(LIST):
temp = input("enter what you want to search for")
tempList = []
for i in LIST:
if str(i._file1__data) == temp:
tempList.append(i)
for i in tempList:
print(tempList._file1__data)
答案 0 :(得分:2)
只需import
变量或设置工厂函数将其吐出。例如,如果您有像
project/
__init__.py
app.py
config.py
app.py
可能需要从mainList
导入config.py
。那么,在app.py
只是
from config import mainList
瞧。您现在可以在app.py
中访问它。您还可以导入整个文件并访问单个变量或函数,如下所示:
import config
mainList = config.mainList
如果它在子目录中,如
project/
__init__.py
app.py
otherstuff/
__init__.py
config.py
你可以
from otherstuff.config import mainList
但是你的子目录中必须有一个__init__.py
才能这样做(即使__init__.py
完全为空)。
<强>更新强>
好吧,我认为您要做的就是将mainList
保留在自己的文件中,并使用search(list)
函数将其“存储”在那里。然后你有file1
和file2
相互引用(当你这样做时,它被称为循环导入,而且它很少是你想要的)。
问题是,用这样的目录结构实现你想要的东西
app/
mainFile.py
file1.py
file2.py
mainFile.py
所需要的只是
# mainFile.py
import file1
并在file1.py
# file1.py
import file2
# Maybe assign some variables for easier access
mainList = file2.mainList
search = file2.search
# And your code
class Library:
pass
file2.py
不应依赖file1.py
或导入流中较高的任何其他文件中的任何信息,并且 应该设置为获取任何列表并搜索它,而不仅仅是来自file1.py
的列表。 When you import a second file that in turn imports the first file, it can cause you a lot of headaches in Python(我之前提到的“循环导入”;有关它们的信息可以在文章的底部找到)。如果file2.py
中的内容确实或必须依赖于file1.py
,那么您应该将其内容移至file1.py
。
既然您可以访问mainFile.py
中的所有数据和结构,那么您可以按照自己的意愿操纵它们。当解释器以mainFile.py
运行'__main__'
时,它所关心的就是mainFile.py
中的内容。自您导入file1.py
和file2.py
后,它们就在那里,可以在您的表达式中使用。需要搜索列表?通过它创建Library()
然后search()
的实例,可能是这样的(mainFile.py
):
# mainFile.py
import file1
library = file1.Library()
search = file1.search # Remember we imported search() from file2.py into file1.py
# Write your logic here
同样,当翻译运行时,只有你在mainFile.py
中所拥有的东西很重要,并且你拥有所需的一切,所以你很好。 search()
和其他特定于模块的变量,函数,方法或属性不能以您在原始问题中编写它们的方式相互依赖;如果他们做的事情开始变得非常混乱。
答案 1 :(得分:1)
由于模块在python中充当singletons,你可以这样做:
在MainFile.py
import tools
mainList = ["Hello", "Python"]
# this is very important to prevent circular imports!
if __name__=='__main__':
# code...
另一个tools.py
import MainFile
# prints out ["Hello", "Python"]
print MainFile.mainList
但不要这样做。这实际上是不好的做法; - )