关于python中的导入(import)包和模块的问题详解

首先目录结构如下
在这里插入图片描述
hello.py定义如下

print(__name__)
def h():
    print("hello world!!!!!!!!!!!!!!!!")

main.py定义如下

import hello
hello.h()

运行main.py,结果如下

hello
hello world!!!!!!!!!!!!!!!!

得出几个结论
1.import 可以导入同级模块(hello.py)
所谓同级可以理解为在同一目录(包)下
2.import 导入hello.py会先执行hello.py,还有,print(__name__)如果如果模块是被直接运行的,则结果为__main__,如果模块是被导入的,则结果为此模块名(hello).
3.想要避免被导入的模块中出现print的结果
使用如下代码,此方法用于模块测试

if __name__=="__main__":
	print("hello python")

我们继续研究
father包下的__init__.py定义如下

import hello
PI=3.14

修改main.py如下,增加了几行代码

import hello
hello.h()
import father
print(father.PI)
print("world")

main.py执行结果:

hello
hello world!!!!!!!!!!!!!!!!
3.14
world

得到几个结论
1.循环导入只会执行一次(第一次main->hello,第二次main->father->hello,只print了一次__name__(也就是hello))
2.包的内容在__init__.py中,我们把包当成一个特殊的可以装子模块的模块

接下来我们探索子包中的导入问题
基础知识: from A import B
用来导入A路径(如果是多级路径,用点连接)下的B模块,或者是B对象
举个栗子

#导入模块

from father import son

#导入某个模块中的对象(类,函数,变量)
#PI为father包中__init__.py下的一个变量

from father import PI

sondir中的__init__.py如下所示

SONPI=3.141592653

sondir中的grandson.py

from father import PI
from sondir import SONPI
print(PI)
#这个函数在下个测试会使用到!
def grandson_func():
    print("grandson's   func")

尝试执行grandson.py,报错

ModuleNotFoundError: No module named 'sondir'

用相对路径试试

from . import SONPI

还是报错

ImportError: cannot import name 'SONPI'

再试试从绝对路径,这次从father开始

from father.sondir import SONPI

!!!过了过了
执行结果如下

hello
3.14

由此我们得出结论,在一个包下的模块,不能通过from . import 这种相对路径去访问包这个模块
(也就是__init__.py中的内容的你可以把它当做父级别模块看待 , 如果要通过绝对路径访问,必须从根目录开始(father在根目录下,从father开始)

但是你说我非要用from sondir import grandson访问行不行?也是可以的,在grandson.py中加入以下代码

import sys
sys.path.append("..")

把grandson的父目录,也就是sondir以及同级目录加入模块搜索路径,解释器会去这个路径找你的包
据说python3.6.7以上不行,还好我是3.6.3

最后我们看一下包与包之间的导入
father包下的mod.py(与sondir2,sondir同级)

def modd():
    print("<<<<<<<<<<mod>>>>>>>>>>>>")

sondir2包下的2个文件如下
init.py 空的
granddaughter.py

import sys
sys.path.append("..")
from sondir import grandson
import mod
mod.modd()
grandson.grandson_func()

granddaughter.py运行结果

hello
3.14
<<<<<<<<<<mod>>>>>>>>>>>>
grandson's   func

可以发现印证了我们上面描述的过程
python在sondir这一级别(father以下)找到了sondir,成功导入了grandson.py,同时也成功找到了同级的mod.py

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值