教程集 www.jiaochengji.com
教程集 >  Python编程  >  python进阶  >  正文 python中如何引入包?

python中如何引入包?

发布时间:2021-01-24   编辑:jiaochengji.com
教程集为您提供python中如何引入包?等资源,欢迎您收藏本站,我们将为您提供最新的python中如何引入包?资源

python中如何引入包?

1、有2个模块功能有些联系

receiveMsg.py和sendMsg.py都在msg文件夹里面。

2、使用import 文件.模块的方式导入

在桌面创建demo.py文件,并把receiveMsg.py和sendMsg.py使用import文件.模块的方式导入demo.py文件。

receive.py模块

def receiveMessage():
    print("正在接受消息...")
send.py模块
def sendMessage():
    print("正在发送消息...")
demo.py模块
import msg.send
import msg.receive
msg.send.sendMessage()
msg.receive.receiveMessage()

运行结果为:

正在发送消息...
正在接受消息...

相关推荐:《Python视频教程》

3、使用from文件夹import模块的方式导入

demo.py模块
from msg import *
send.sendMessage()
receive.receiveMessage()

运行结果为:

Traceback (most recent call last):
  File "C:\Users\Se7eN_HOU\Desktop\deno.py", line 2, in <module>
    send.sendMessage()
NameError: name 'send' is not defined

这个时候我们使用msg下面的模块失败,提示我们没有定义模块

4、在msg文件夹下创建 _ _init_ _.py 文件

5、在_ _init_ _.py文件中写入

_all__ = ["send","receive"] 

6、重新使用from文件夹import模块的方式导入

from msg import *
send.sendMessage()
receive.receiveMessage()

运行结果为:

正在发送消息...
正在接受消息...

总结:

包将有联系的模块组织在一起,即放到同一个文件夹下,并且在这个文件夹创建一个名字为__init__.py 文件,那么这个文件夹就称之为包

有效避免模块名称冲突问题,让应用组织结构更加清晰。

您可能感兴趣的文章:
python中如何引用包
字符串在Python中如何表达出来
python如何注释整行代码
Python中包如何嵌套
Python字符串详解
python input函数如何不要引号
Python包的循环导入是什么
Python 2.x和Python 3.x,初学者应如何选择?
Python基本语法与变量的相关介绍
在Python中如何获取元素在数组中的索引号?

[关闭]
~ ~