[语言基础] 模块化

准备:目录结构与说明

top
│  1.txt
│  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包里面的多个模块,怎么办?
->
# father1 -> __init__.py
from . import module1,module1_1

# main.py
import father1
print(father1.module1.name)
 

猜你喜欢

转载自www.cnblogs.com/remly/p/11581991.html
今日推荐