Python通过import实现模块导入与共享,.py文件即模块,可封装函数、变量供其他文件使用;支持多种导入方式如from...import、import as及from...import *(不推荐);通过__all__列表控制模块对外暴露的接口;包(含__init__.py的目录)支持多层结构,可在__init__.py中预导入内容简化调用,从而实现代码组织与复用。

在 Python 中,并没有直接的“导入导出”功能像数据库那样,但通过 import 机制,可以实现代码模块之间的导入与共享,从而达到组织和复用的目的。下面说明如何使用 import 进行模块的导入,以及如何设计模块以便被其他文件“导出”使用。
什么是模块导入
Python 中一个 .py 文件就是一个模块。你可以将功能封装在某个文件中,然后在其他文件中通过 import 来使用它。
例如,你有一个文件叫 utils.py:
# utils.py
def add(a, b):
return a + b
<p>def multiply(a, b):
return a * b</p><p>PI = 3.14159</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2155" title="AI小聚"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175680303065491.png" alt="AI小聚" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2155" title="AI小聚">AI小聚</a>
<p>一站式多功能AIGC创作平台,支持AI绘画、AI视频、AI聊天、AI音乐</p>
</div>
<a href="/ai/2155" title="AI小聚" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>在另一个文件中,比如 main.py,你可以这样导入并使用:
# main.py import utils <p>print(utils.add(2, 3)) # 输出: 5 print(utils.multiply(2, 4)) # 输出: 8 print(utils.PI) # 输出: 3.14159</p>
不同的导入方式
除了完整导入,还有几种常用方式来更灵活地使用模块内容:
- from ... import ...:只导入特定函数或变量
- import ... as ...:给模块起别名
- from ... import *:导入所有公开名称(不推荐)
from utils import add, PI print(add(5, 6)) # 可以直接用 add,不用加 utils.
import utils as u print(u.add(1, 2))
from utils import * print(add(1, 2)) # 直接调用,但容易造成命名冲突
控制“导出”的内容
当你希望别人导入你的模块时只暴露特定内容,可以用 __all__ 列表来声明哪些名字可以被 from module import * 导入。
# utils.py __all__ = ['add', 'PI'] # 只允许 add 和 PI 被 * 导入 <p>def add(a, b): return a + b</p><p>def multiply(a, b): # 不在 <strong>all</strong> 中,不会被 from utils import <em> 导入 return a </em> b</p><p>PI = 3.14159</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>
这样,即使使用 from utils import *,multiply 也不会被导入。
包的导入(多层目录)
当项目变大时,会使用包(包含 __init__.py 的文件夹)来组织模块。
目录结构示例:
myproject/ ├── __init__.py ├── math_utils/ │ ├── __init__.py │ └── operations.py └── main.py
在 operations.py 中定义函数:
def divide(a, b):
return a / b
在 main.py 中导入:
from math_utils.operations import divide print(divide(10, 2))
你也可以在包的 __init__.py 中提前导入内容,简化外部调用:
# math_utils/__init__.py from .operations import divide
之后就可以这样用:
from math_utils import divide
基本上就这些。通过 import 机制,Python 实现了良好的模块化支持,“导出”靠的是合理组织模块和使用 all 控制接口,“导入”则灵活多样,适合不同场景。










