python的包

包可用于将一组模块分组到一个自定义的包名称下。
[root@VM_131_54_centos tt]# tree

.
|– main.py
|– recv
| -- recvmsg.py
– send
|– init.py
|– init.pyc
|– sendmsg.py

send是个目录,且里面有个init.py就可以成为一个包。而recv目录下没有。



在这两个目录的上层测试是否能够被导入,可以看出,没有init.py的就导入失败。

[root@VM_131_54_centos tt]# ls
main.py  recv  send
[root@VM_131_54_centos tt]# ipython
In [1]: from recv.recvmsg  import *
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-ed208f11484c> in <module>()
----> 1 from recv.recvmsg  import *

ImportError: No module named recv.recvmsg

In [2]: from send.sendmsg import *  #导入成功



init.py文件可以为空,里面什么都不写,只有一个空文件。只要是导入模块时,该模块是第一次导入,就会执行init.py中的代码。如:sendmsg被导入过一次,那么有sendmsg.pyc文件,此时再次导入就不会执行init.py。


init.py模块为空的情况下,只import 包名 ,如:import send 。那么不会导入包中所包含的所有模块。如下所示:

[root@VM_131_54_centos tt]# ipython
In [1]: import send
In [2]: send.sendmsg.sendMsg()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-731caa8df27a> in <module>()
----> 1 send.sendmsg.sendMsg()

AttributeError: 'module' object has no attribute 'sendmsg'



但是如果在init.py中添加如下语句就可行:

[root@VM_131_54_centos send]# cat __init__.py
import sendmsg  #添加一句
[root@VM_131_54_centos send]# ls
__init__.py  __init__.pyc  sendmsg.py  sendmsg.pyc

[root@VM_131_54_centos tt]# ls
main.py  recv  send
[root@VM_131_54_centos tt]# ipython
In [1]: import send
In [2]: send.sendmsg.sendMsg()
已经发送信息

这样只导入包的话,会执行init.py中的语句,这样就自动导入了sendmsg模块。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值