大型Python包含
时间:2020-03-05 18:50:23 来源:igfitidea点击:
我有一个要包含在Python中的文件,但是包含的文件相当长,能够将它们拆分成多个文件要整整齐齐,但是随后我必须使用多个include语句。
有什么办法可以将几个文件组合在一起并一次包含所有文件?
解决方案
回答
是的,请查看http://docs.python.org/tut/node8.html中的" 6.4软件包"部分:
基本上,我们可以将一堆文件放入目录中,并将__init__.py文件添加到目录中。如果目录位于PYTHONPATH或者sys.path中,则可以执行"导入目录名"以导入目录中的所有内容,或者执行"导入目录名.some_file_in_directory"以导入目录中的特定文件。
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as "string", from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
回答
- 将文件放在一个文件夹中。
- 将__init__.py文件添加到该文件夹。在__init__.py中进行必要的导入
- 用一个替换多个导入:import folder_name
请参阅Python软件包管理