1. 导入模块
1.1 导入模块的三种方式
import 模块
from 模块 import 功能名
from 模块 import *
- 代码解释
import math
print(math.sqrt(9))
from math import sqrt
from math import *
print(sqrt(9))
1.2 导入模块时设别名
import 模块 as 别名
from 模块 import 功能名 as 别名
定义别名后原名称就不能使用了
import math as mm
# print(math.sqrt(9)) 定义别名后原名称就不能使用了
print(mm.sqrt(9))
from math import sqrt as st
print(st(9))
2. 自定义模块
2.1 写模块
模块定义 :一个模块就是一个.py
文件,里面的函数就是 功能 ,
为什么需要模块: 对于经常需要调用的功能代码独立出来,而无需每次将功能代码写在代码中
2.2 测试模块
对于写好的模块需要测试,对于内部测试的代码可以通过if __name__ == '__main__'
隐藏在模块中,而避免调用模块时使用测试代码
-
__name__
在模块内测试时表示'__main__'
-
__name__
在模块被调用测试时表示模块名
def mutipliy(a, b):
print(a + b)
if __name__ == '__main__': # 内部测试代码
mutipliy(1, 1)
2.3 不同模块同名函数同时调用
调用最后一个同名函数
当通过from 模块 improt *
时
# 模块1代码
def my_test(a, b):
print(a + b)
# 模块2代码
def my_test(a, b):
print(a - b)
# 导入模块和调用功能代码
from my_module1 import my_test
from my_module2 import my_test
# my_test函数是模块2中的函数
my_test(1, 1)
引入模块的函数和自定义的函数同名时,仍调用最后一个函数
from math import sqrt
def sqrt():
print('haha')
sqrt() # 输出haha
3. 模块定位顺序
- 当前目录
- 如果不在当前目录,Python则搜索在shell变量PYTHONPATH下的每个目录。
- 如果都找不到,Python会察看默认路径。
4. __all__
筛选模块中功能
- 定义
当使用from 模块 import *
时,不能为import 模块
__all__
列表中包含的功能名称才能使用 - 语法
__all__ = ['模块名','模块名']
- 代码解释
# 模块mathh中
__all__ = ['test1'] # 筛选模块
def test1():
...
def test2():
...
# 调用模块
from mathh import *
test1()
test2() # 调用出错 NameError: name 'test2' is not defined
5. 包
- 方法一:
- 导包:
import 包名
- 调用:
包名.模块名.功能名
- 方法二:
- 先在包的
__init__.py
中__all__
列表中添加模块名 - 导包:
from 包名 import *
- 调包:
模块名.功能名
- 代码解释
# 方法一: import 包名
# import my_package.my_module1
# my_package.my_module1.test()
# 方法二:from 包名 import *
# 首先需要在__init__.py中_all__列表中添加模块名
from my_package import *
my_module1.test()
6. 总结
- 模块
import 模块
from 模块 import 功能名
from 模块 import *
- 同名模块、函数注意事项
- 包
import 包名
from 包名 import *
__all__ = []
筛选