
在python中,代码的组织方式主要依赖于模块(module)和包(package)。
正确地组织代码为模块和包,不仅能提高代码的复用性,还能使项目结构更加清晰,便于管理和维护。
考虑以下项目文件结构:
Parent/ ├── test/ │ └── testFunc.py └── app.py
其中testFunc.py定义了两个函数:
# Parent/test/testFunc.py
def testRound(value):
return int(value + 0.5)
def isEligible(name, age):
if age >= 18:
return 'Hello ' + name + ', ' + 'you are eligible for driving'
else:
return 'Hello ' + name + ', ' + 'you are not eligible'而app.py尝试从test目录下的testFunc.py导入并使用这些函数:
立即学习“Python免费学习笔记(深入)”;
# Parent/app.py
from test.testFunc import *
print(isEligible('Shakya', 18))
print(testRound(4.5))当直接执行app.py时,Python解释器会报告ModuleNotFoundError。这是因为在上述文件结构中,test目录仅仅是一个普通的目录,而不是一个Python包。Python解释器无法识别test.testFunc这样的导入路径。
解决ModuleNotFoundError的关键在于将test目录声明为一个Python包。这通过在test目录下创建一个空的__init__.py文件来实现。
最终的文件结构应如下所示:
Parent/ ├── test/ │ ├── __init__.py # 新增文件 │ └── testFunc.py └── app.py
__init__.py文件可以是完全空的,它的存在本身就足以让Python将test目录识别为一个包。
1. testFunc.py (内容不变)
# Parent/test/testFunc.py
def testRound(value):
return int(value + 0.5)
def isEligible(name, age):
if age >= 18:
return 'Hello ' + name + ', ' + 'you are eligible for driving'
else:
return 'Hello ' + name + ', ' + 'you are not eligible'2. app.py (内容不变)
# Parent/app.py
from test.testFunc import *
print(isEligible('Shakya', 18))
print(testRound(4.5))3. __init__.py (内容为空)
在Parent/test/目录下创建名为__init__.py的空文件。
运行结果:
在上述文件结构调整后,从Parent目录或其子目录(如Parent本身)运行app.py时,将不再出现ModuleNotFoundError。Python解释器现在能够正确地识别test为一个包,并从中导入testFunc模块。
Hello Shakya, you are eligible for driving 5
__init__.py的用途:
Python解释器查找路径 (sys.path):
相对导入与绝对导入:
在Python中实现跨目录的模块导入,关键在于正确地构建Python包。通过在包含模块的目录中放置一个空的__init__.py文件,该目录就被Python解释器识别为一个包,从而允许通过点号(.)语法进行层次化导入。这种机制不仅解决了ModuleNotFoundError的问题,也促进了更清晰、更易于管理的项目结构。理解__init__.py的作用以及Python的模块查找机制,是编写健壮、可维护的Python项目的基础。
以上就是Python模块与包:跨目录导入函数的最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号