准备:目录结构与说明
top │ main.py │ ├─father1 │ module1.py │ module1_1.py │ __init__.py │ └─father2 │ module2.py │ __init__.py │ └─son2 module2_son2.py __init__.py
#module1.py name = 'father1' #module1_1.py age = '12' #module2.py name = 'father2'
#module2_son2.py name = 'son2'
模块导入
#从 文件夹father1中 导入 模块module1 from father1 import module1 print(module1.name) #father1
包导入
''' import 风格 缺点:使用的时候需要再重复一遍import的内容 ''' import father1.module1 print(father1.module1.name) #father1 ''' from xxx import xxx 风格 ''' #从 文件夹father1 -> 模块module1 中导入 变量name from father1.module1 import name print(name) #father1 #从father2son2文件夹中导入模块module2_son2 from father2.son2 import module2_son2 print(module2_son2.name) #son2
问题1:可不可以直接import father1呢?
->不行,不能直接import文件夹,import的必须是模块或者变量
问题2:那么我想import father1,怎么办呢?
top │ main.py │ ├─father1 │ module1.py │ module1_1.py │ __init__.py │ └─ 略...
# father1 -> __init__.py from . import module1,module1_1 # main.py import father1 print(father1.module1.name)
问题3:在module1.py中相对导入同目录的模块module1_1,然后运行module1.py,结果报错: cannot import name 'module1_1' from '__main__' (.module1.py) ,如何解决?
top
│ main.py
│
├─father1
│ module1.py
│ module1_1.py
│ __init__.py
│
└─ 略...
# module1.py from . import module1_1 ''' 运行module1.py: ..略.. opfather1> python .module1.py Traceback (most recent call last): File ".module1.py", line 1, in <module> from . import module1_1 ImportError: cannot import name 'module1_1' from '__main__' (.module1.py) '''
答:运行顶层文件模块 -> main.py
# main.py from father1 import module1 print(module1.module1_1.age)
原因:参考Python学习手册p583
相对导入适用于只在包内导入。这种功能的模块搜索路径修改只应用于位于包内的模块文件中的import语句。位于包文件之外的通常的导入将像前面所介绍的那样工作,首先自动搜索包含了顶级脚本的目录。