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">
<a class="aritcle_card_img" href="/ai/1989">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175679968212304.png" alt="AppMall应用商店">
</a>
<div class="aritcle_card_info">
<a href="/ai/1989">AppMall应用商店</a>
<p>AI应用商店,提供即时交付、按需付费的人工智能应用服务</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="AppMall应用商店">
<span>56</span>
</div>
</div>
<a href="/ai/1989" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="AppMall应用商店">
</a>
</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 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 控制接口,“导入”则灵活多样,适合不同场景。
以上就是python使用import导入导出的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号