[语言基础] 模块、包遇到的问题

准备:目录结构与说明

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

#从father2\son2文件夹中导入模块module2_son2
from father2.son2 import module2_son2
print(module2_son2.name)  #son2

问题1:可不可以直接import father1呢?

->不行,不能直接import文件夹,import的必须是模块或者变量

问题2:我想要直接import一个包,或者说同时import包里面的多个模块,怎么办?

top
│  main.py
│  
├─father1
│      module1.pymodule1_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:
..略..\top\father1> 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语句。位于包文件之外的通常的导入将像前面所介绍的那样工作,首先自动搜索包含了顶级脚本的目录。

转载于:https://www.cnblogs.com/remly/p/11581991.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值