用Python和__init__.py导入模块 [英] Importing modules in Python and __init__.py
问题描述
我一直在阅读 __ init __。py
文件的功能。据说我们在包含模块的文件夹中需要一个空的 __ init __。py
文件,以便可以导入这些模块。但是,我尝试将文件夹路径添加到PYTHONPATH(Windows 7中的环境变量)。虽然此文件夹不包含 __ init __。py
文件,但我仍然可以从该文件夹导入模块。你能否解释如何在没有 __ init __。py
的情况下导入这些模块?
I have been reading about the function of __init__.py
file. It is said that we need an empty __init__.py
file in the folder which contains modules, so that these modules can be imported. However, I tried adding a folder path to PYTHONPATH (Environment Variable in Windows 7). Although this folder does not contain an __init__.py
file, I can still import the modules from that folder. Could you please explain how these modules can be imported without the existence of an __init__.py
?
谢谢,
祝你好运
推荐答案
__ init__.py
将文件夹转换为包。这对于创建一种模块层次结构非常有用,您可以在其中使用如下导入语句:
__init__.py
turns a folder into a package. This is useful to create a sort of hierarchy of modules, where you can have import-statements like this:
import mymodule.cool.stuff
如果没有套餐,这是不可能的。
This is not possible without packages.
这篇关于用Python和__init__.py导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!