我对python还不熟悉,但我仍然在为noob的问题感到抱歉。我目前正在开发一个跨多个文件的程序,其中一个是“主文件”,它是唯一运行的文件。我正在尝试创建一个名为mainList的变量,以使它在所有文件中都可以访问。我希望它是这样,如果我在一个文件中更改它,它会在其他文件中更新。 我尝试使用全局,但它没有更新所有文件中的列表。 这是我的三个文件的一个非常简化的版本:
这是主文件:#I only run mainFile
import file1
import file2
file2.search(mainList)
这是文件1:
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.
这是文件2:
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)
由于模块在python中充当singletons,您可以这样做:
在你的
MainFile.py
另一个
tools.py
但不要这样做。这真是个坏习惯
只需
import
变量或设置工厂函数即可将其输出。例如,如果您有一个目录结构app.py
可能需要从config.py
导入mainList
。嗯,在app.py
只是瞧。您现在可以在
app.py
中访问它。您还可以导入整个文件并访问单个变量或函数,如下所示:如果它在一个小区里,比如
你可以的
但是您必须在子目录中有一个
__init__.py
才能这样做(即使__init__.py
是完全空的)。你知道吗更新
嗯,我想你要做的是把
mainList
保存在它自己的文件中,然后用search(list)
函数把它“存储”在那里。然后file1
和file2
相互引用(这样做时,称为循环导入,很少是您想要的)。你知道吗问题是,用这样的目录结构来实现你想要的
在
mainFile.py
中需要做的就是在
file1.py
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
中的所有数据和结构,您可以按照自己的意愿对它们进行操作。当解释器以'__main__'
的形式运行mainFile.py
时,它只关心mainFile.py
中的内容。既然导入了file1.py
和file2.py
,它们就在那里,可以在表达式中使用。需要搜索列表吗?创建一个Library()
的实例,然后通过它search()
,可能是这样(mainFile.py
):同样,当解释器运行时,只有你在
mainFile.py
中拥有的东西才重要,你在那里拥有你所需要的一切,所以你很好。search()
和其他特定于模块的变量、函数、方法或属性不能像您在原始问题中编写它们的方式那样相互依赖;如果它们真的开始变得非常混乱。你知道吗相关问题 更多 >
编程相关推荐