【总结】包和模块(2022.4.27)
1.模块
1.1 模块是什么
python中一个py文件就是一个模块
1.2 如何在模块中使用另一个模块的内容
1)前提:被使用的模块的模块名(py文件的文件名)必须符合变量名的要求(是标识符,不是关键字)
2)能被使用的内容:所有的全局变量
3)怎么用:使用别的模块中的内容前,必须先导入模块
1.3 导入模块的方式
1)import 模块名 - 导入指定模块;导入过后可以通过 ‘模块名.xxx’ 的方式使用这个模块中的所有全局变量
import test
print(test.a)
test.func1()
2)from 模块名 import 变量名1, 变量名2,… - 导入指定模块中指定变量;导入后可以直接使用指定变量
from test import a, func1
print(a)
print(func1)
3)from 模块名 import * - 导入指定模块中所有变量;导入后可以直接使用所有变量
from test import *
print(a)
print(func1)
4)import 模块名 as 新模块名 - 直接导入指定模块,并且对模块进行重命名,重命名后需要通过新模块名来代替原模块名使用模块
import test as ts
print(ts.a)
ts.func1()
print(ts.b)
5)from 模块名 import 变量名1 as 新变量名1, 变量名2 as 新变量名2,…
from test import a as aa, func1 as fu
print(aa)
print(fu)
2.导入原理与阻止导入
2.1 导入模块的原理
不管以什么样的方式导入模块,导入模块的时候系统会自动进入这个模块执行这个模块中所有的代码
2.2 阻止导入
因为导入模块的时候默认会执行模块中所有的代码,就会导致有些完全没有必要在导入的时候执行的代码被执行
如果希望导入模块的时候,某些代码可以不执行,就需要去阻止代码在被导入的时候被执行
阻止方法:将不需要被执行的代码放到main对应的if条件语句里面
# 在这个if语句里面的代码在被别的模块导入的时候不会被执行
if __name__ == '__main__': # 需要添加在被导入的模块中
pass #需要被阻止运行的所有代码
# 举个栗子(这段代码应存在于被导入的模块中)
def downlod_movie(neme):
print(f'============{name}开始下载==============')
print('')
print('')
print(f'============{name}下载结束==============')
# 在这个if语句里面的代码在被别的模块导入的时候不会被执行
if __name__ == '__main__':
names = ['海上钢琴师', '绿皮书']
for name in names:
downlod_movie(name)
################'__main__'代表运行这段代码的模块的文件名
3.包
3.1 包的定义
包就是存放 "__init__.py"
文件的文件夹
3.2 怎样使用包中的内容(导入包,使用模块,使用模块中的变量)
方法1: import 包名 - 直接导入包,导入包后可以通过’包.xxx’的方式使用__init__.py里面所有的全局变量
#================导入方式1:直接导入包================
import package1
print(package1.y)
package1.func3()
方法2:import 包名.模块名 - 导入指定包中的指定模块,导入后可以通过’包名.模块名.xxx’来使用指定模块中所有的全局变量
#================导入方式2:直接导入包中的指定模块================
import package1.test2
print(package1.test2.z)
package1.test2.func2()
# 改良
import package1.test2 as test
print(test.z)
test.func3()
方法3:from 包名 import 模块名1, 模块名2,… - 导入包中的指定模块,导入后通过’模块名.xxx’使用对应的模块中的内容
#================导入方式3:直接导入包中的指定模块================
from package1 import test2,test3
print(test2.z)
test2.func3()
print(test3.z)
test3.func4()
方法4:from 包名 import * - 导入包中__ init __.py文件中所有的全局变量
#================导入方式4:直接导入包中__init__.py文件中所有的全局变量================
from package1 import *
print(y)
func3()
**方法5:**from 包名.模块名 import 变量1,变量2,… - 导入指定模块中的指定变量
#================导入方式5:直接导入包中指定模块中的指定变量================
from package1.test3 import z,func4
print(z)
func4()
注意:可将包中需要的模块在__init__.py
模块中先行导入,即可使用方法1和方法4直接导入模块
# 当前为 __init__.py
# 1. 关联导入
from package1 import test2, test3, test4
# 2. 创建快捷键
from package1.abc.test6 import abc
4.常用模块
4.1 数学模块
import math, cmath
# math - 针对普通数字对应的数学模块
# cmath - 复数数字对应的数学模块
# complex - 复数: a + bi
# 1. 补充复数 - python支持复数
# 格式:a + bj
num1 = 10 + 3j
num2 = 5 - 6j
print(num1 + num2) # (15-3j)
print(num1 * num2) # (68-45j)
# 1.浮点数转整数
# 1)int(浮点数) - 直接去掉小数点位
print((int(1.23))) # 1
print((int(-1.23))) # -1
# 2)math.ceil(浮点数) - 向大取整(向上取整)
print(math.ceil(1.98)) # 2
print(math.ceil(1.002)) # 2
print(math.ceil(-1.23)) # -1
# 3)math.floor(浮点数) - 向小取整(向下取整)
print(math.floor(1.98)) # 1
print(math.floor(1.002)) # 1
print(math.floor(-1.23)) # -2
# 4)round(浮点数) - 四舍五入
print(round(1.68)) # 2
print(round(1.402)) # 1
# 注意:x.5的时候,x如果是奇数就入,x是偶数就舍
print(round(1.5)) # 2
print(round(4.5)) # 4
# 2. 求绝对值
# 1)abs(数字)
print(abs(-23)) # 23
print(abs(-23.45)) # 23.45
# 2)fabs(数字)
print(math.fabs(-23)) # 23.0
print(math.fabs(-23.45)) # 23.45
4.2 随机模块
import random
# 1.创建随机整数:randint(a, b) - 产生[a,b]的随机整数
print(random.randint(1,2))
# 2.创建随机小数:random() - 产生[0, 1)的随机小数
print(random.random())
# 产生 0-100的随机小数
print(random.random()*100)
print(float(f'{random.random() * 100:.2f}'))
print(int(random.random() * 10000 / 100))
# 产生一个30~100的随机小数
print(int(random.random() * 70 + 30))
# 产生一个25~55的随机小数
# 0~1 * 30 -> 0~30 + 25 -> 25~55
print(int(random.random() * 30 + 25))
# 3.在指定的等差数列中随机获取一个数:randrange(N) randrange(M, N) randrange(M, N, step)
print(random.randrange(0, 100, 2))
print(random.randrange(10, 61, 10))
# 4.洗牌:shuffle(列表) - 将列表中的元素顺序随机打乱
nums = [10,20,30,40,50]
random.shuffle(nums)
print(nums)
# 5.抽牌:
# 1)choice(序列) - 从指定序列中随机获取一个元素
print(random.choice('abc123'))
print(random.choice(nums))
# 2)
## choices(序列) - 从指定序列中随机获取多个元素, 返回值是列表 (有放回抽取)
print(random.choices(nums))
print(random.choices('abc123'))
## choices(序列, k=次数) - 从指定序列中随机获取指定个数元素, 返回值是列表 (有放回抽取)
print(random.choices(nums, k=2))
print(random.choices('abc123', k=2))
## choices(序列, k=次数)
# weights:[1, 1, 1, 1, 1] 1/5
# weights:[1, 2, 1, 1, 1] 1/6, 2/3, 1/6, 1/6, 1/6
list1 = ['谢谢', '5元红包', '100红红包', 'ipone13','macPro','100万']
print(random.choices(list1, weights=[100000, 10, 5, 3, 2, 1]))
# 3)sample() - (无放回抽样)
# sample(序列, k=次数) - 3.9以前的版本
# sample(序列, k=次数, counts=权重列表) - 3.9以后的版本
print(random.choices([10,20], k=2))
print(random.sample([10,20], k=2))
print(random.sample(list1, k=1, counts=[100000, 10, 5, 3, 2, 1]))
4.3 time模块
时间戳 : 通过保存一个时间到1970年1月1日0时0分0秒(格林威治时间)之间的时间差(单位是秒)来保存一个是时间值。
**使用时间戳保存时间的好处:**a.节约内容 b.方便加密
from time import *
# 1. time() - 获取当前时间,返回的是时间戳
t1 = time()
print(t1) # 1651052175.375231
# 2.
# localtime() - 获取本地当前时间,返回的是结构体时间
# localtime(时间戳) - 将时间戳转换成结构体时间
t2 = localtime()
print(t2) #tm_wday - 星期(0(周一)~6(周天))
t3 = localtime(0)
print(t3)
# 1. time() - 获取当前时间,返回的是时间戳
# 2.
# 1)localtime() - 获取本地当前时间,返回的是结构体时间
# 2)localtime(时间戳) - 将时间戳转换成本地时间对应的结构体时间
# 结构体时间:time.struct_time(tm_year=2022, tm_mon=4, tm_mday=28, tm_hour=9, tm_min=37, tm_sec=13, tm_wday=3, tm_yday=118, tm_isdst=0)
t1 = localtime()
print(t1)
# 通过结构体时间获取具体的时间信息:时间对象.时间属性名
print('年:', t1.tm_year)
# 3.将字符串时间转换成结构体时间
"""
strptime(字符串时间,时间格式)
时间格式 - 包含时间占位符的字符串
%Y - 年
%m - 月
%d - 日
%H - 时(24小时制)
%I - 时(12小时制)
%M - 分
%S - 秒
%a - 星期缩写
%A - 星期全拼
%b - 月份单词缩写
%B - 月份单词全拼
%p - 上午或下午(AM or PM)
"""
t2 = '2003-5-8'
t3 = strptime(t2, '%Y-%m-%d')
print(t3)
print(t3, t3.tm_wday)
t4 = strptime('2022-2-10 9:24:38','%Y-%m-%d %H:%M:%S')
print(t4)
# 4.将结构体时间转换成字符串时间
# strftime(时间格式, 结构体时间)
t5 = localtime()
print(f'{t5.tm_year}/{t5.tm_mon}/{t5.tm_mday} {t5.tm_hour}:{t5.tm_min}:{t5.tm_sec}')
result = strftime('%Y-%m-%d %I:%M:%S %p %A %B %z %c', t5) # 2022-04-28 09:59:57 AM Thursday April +0800 Thu Apr 28 09:59:57 2022
print(result)
# 5.将结构体时间转换成时间戳:mktime(结构体时间)
t6 = mktime(t5)
print(t6)
# 6. 睡眠:sleep(秒)
sleep(2)
print('======end======')