第九章 模块和包
“”"
模块
包
具体模块
math包
随机包
时间日期包
date类
time类
datetime类
一、模块
1.模块的定义
import keyword
print(keyword.kwlist)
为什么要有模块:
一个文件就是一个模块,从文件物理的角度,从逻辑的角度说,一个模块也是存在命名空间中。
划分模块的好处:
"""
1. 一个模块提供了一个独立的命名空间,解决命名冲突
2. 按照模块划分不同功能,不同的功能在不同py文件开发。
3. 提高代码的复用性
"""
代码共享:svn cvs gitpub
2. 模块的使用
模块之间如何调用。
两种方式,(1)import (2) from...import...
(1)import
【导入语法】:import 要导入的模块名(如果有多个模块,用逗号分隔即可)
当导入了一个模块之后,计算机python做了什么?
当import一个模块(py),则会把被导入模块的代码执行一次。
如果再次导入,则不会重复执行。
习惯上,将导入全部放在代码的面前
【使用导入模块的语法】:模块名.名称
import math
print(math.pow(3,4))
导入自定义模块
import another
print(another.x)
another.y()
使用import,会避免名字冲突,因为使用导入模块的名字,前面要有 模块名.
x=1
print(x)
(2) from 模块名 import 名字
【导入的语法】 from 模块名 import 名字1,名字2
from...import跟import类似,在导入的时候,被执行被导入模块的代码
【使用导入模块的名字语法】
直接使用名字即可
print(x)
x=1
print(x)
from another import x
print(x)
使用from...import的时候要注意,会和当前模块中的名字冲突。
加载的顺序,按照调用顺序的先后
from another import x,y
y()
使用from ..import也可以一次性将被导入模块的所有名字都导入
慎用,因为被导入所有的名字可能会跟当前模块中的名字造成冲突。
from another import *
print(x)
y()
区别:
使用import是一次性将模块下的所有名字都导入 ,使用的是要使用:模块名.名字
from ..import,除了使用*以外,是一次导入模块下的一个名字,使用的时候,直接用名字
3. 模块别名
当导入模块时,可以使用as为模块进行重新指定名字
语法:
"""
import 模块1 as 别名1,模块2 as 别名2....
from 模块 import 名字1 as 别名1 ,名字2 as 别名2....
注意:有了别名,原名字不可用
"""
import another as a1
print(a1.x)
from another import x as x1
print(x1)
"""
别名的好处:
(1)使用别名可以解决当前模块名字跟导入模块名字冲突的问题
(2)当名字特别长的时候,可以起到简化的作用
"""
4.隐藏模块数据
注意:只对from...import * 导入起作用
两种方式
(1)指定不能被导入的名字
方式:在名字前面_,这样名字就不会被导入到其他模块中
from another import *
print(x)
print(_w)
(2)指定要被导入的名字
__all__ 列表,列表中是希望被导入的名字,
一定要指定的是名字,是要""括起来,否则导入的是对象
from another import *
print(x)
print(z)
print(_w)
当一个_起名的变量,会放到__all__中,最终结果是可以被导入的
原因是先加载__all__,然后才去加载其他不需要导入的变量。
5.__name__
在类中,指类的名字
需求:因为在当前模块中导入其他模块,不一定其他模块的所有代码都希望在当前模块中执行。
import another
执行another,__name__
(1)右键执行another,显示模块名 __main__
(2)通过执行day12模块,导入another,间接执行another 显示模块名:another
阻止一部分代码不在导入的模块中执行,可以使用__name__
在被导入模块中加if __name__ =="__main__":,可以让当前模块被导入的时候,不执行if中的代码
习惯上被当做主程序的调用
函数定义、class定义
def a():
pass
if __name__ =="__main__":
a()
6.模块的搜索路径
import random
print(random.randint(1,4))
模块加载的顺序
"""
1. 内建模块中加载
2. 当前脚本所在路径中加载
3. python的环境变量path加载
4. python的安装路径 如:lib
"""
注意:不要使用跟lib库同名的模块名
7.模块的缓存
导入模块的时候,被导入的模块代码除了 if __name__=="__main__"下的内容都会被执行加载一次
每次导入时,被导入模块都被写入缓存
当再次调用import或者from..import的时候,会直接加载缓存文件
写入缓存:加快的模块的加载速度,但是并不能提高模块的执行速度
当导入模块的时候,会创建缓存文件,缓存文件是二进制文件
缓存文件可以脱离源文件执行。
二、包
“”"
包是为了提供模块的分类管理
包有独立的命名空间,可以解决模块名的冲突
“”"
1. 导入包
语法跟模块基本类似
import 包名 as 别名
from 包名 import 模块名 as 别名
import day12.another
from day12.another import x
print(x)
2. __init__.py
每个python的开发包都会具有一个__init__.py
用来对于整个包进行初始化
当加载包的时候,会执行这个包下的init文件
import day12
from day12 import another
print(day12.x)
3.__all__变量
只针对from day12 import *有效,对import,from day12 import y
from day12 import y
from day12 import *
__all__ 是一个列表,指定能够导入的名字
print(y)
print(x)
普通的文件夹跟包的区别:
普通的文件夹没有__init__.py,其他模块无法导入这个包中的文件。
包下有__init__.py,其他模块可以导入包中的文件
三、具体模块
(一)math模块 数学模块
import math
圆周率
print(math.pi)
数学常数
print(math.e)
向上取整
print(math.ceil(3.5))
print(math.ceil(-3.5))
向下取整
print(math.floor(3.5))
print(math.floor(-3.5))
返回常数e的x的幂
print(math.exp(1))
x的y次幂
print(math.pow(2,5))
log ,默认以e为底
print(math.log(8,2))
浮点数的绝对值
print(math.fabs(-3.5))
取余
正数:商向下取整
负数:商向上取整
print(math.fmod(10,-3))
累加和
print(math.fsum([1,2,3,4]))
最大公约数
print(math.gcd(12,15))
返回x的平方根
print(math.sqrt(9))
print(math.sqrt(-9))
(二)随机模块
import random
(1) 产生一个随机数,小数 0<=x<1
print(random.random())
while random!=0:
pass
print()
(2)randint(a,b) a<=x<=b
print(random.randint(1,3))
(3)randrange(start,end,step)
参数的意义跟range类似,相当于从range函数得到的结果中随机选一个
包含起点,不包含终点
print(random.randrange(1,3))
(4)uniform(a,b) 返回a.b之间的浮点数,a<=x<=b
print(random.uniform(1,2))
(5) choice(seq) 从seq中随机选择一个元素
print(random.choice([1,2,3,4,5]))
(6)choices()从序列中随机选择n的元素,还可以设置权重
print(random.choices([1,2,3,4,5],k=3,weights=[1,1,1,1,100]))
随机选择一个数后,还会放回到样本中。
(7)samle()随机选择n个数后,不会放回到样本中。
print(random.sample([1,2,3],2))
(8)shuffle() 就地洗牌
li=[1,2,3,4,5,6]
random.shuffle(li)
print(li)
(三)时间和日期模块
时间:时间
日期:年月日
time datetime
1. time包 时间包
提供了跟时间相关的操作
import time
(1)time.timezone 返回与UTC相差的秒数
UTC:世界标准时间:本初子午线上的时间
北京时间:东八区的时间
print(time.timezone)
(2)time() 从新纪元到当前时间走过的秒数
新纪元:unix产生时间 1970年1月1
print(time.time())
(3)localtime([seconds])
返回从新纪元走过seconds之后的时间。
如果参数不写,默认返回的是本地当前时间
返回一个时间元组
print(time.localtime())
print(time.localtime(1))
(4)gmtime,返回与localtime([seconds])类似 ,返回的是utc时间
print(time.gmtime())
(5)mktime:将时间元组转换成从新纪元到元组指定时间走过的秒数
t=time.localtime()
print(time.mktime(t))
(6)time.ctime() 将从新纪元走过的毫秒数转换成本地时间,str
print(time.ctime())
(7)sleep:将程序暂停的时间
print("暂停之前")
time.sleep(1)
print("暂停之后")
(8)clock 时钟,unix和window下作用不同。
winows下,
第一次调用:cpu的计算时间
第二次调用返回的距离第一次调用该函数所经历的时间
print(time.clock())
time.sleep(1)
print(time.clock())
time.sleep(1)
print(time.clock())
(9)per_counter(),返回精准的性能计数器
包含了sleep函数的时间
start=time.perf_counter()
time.sleep(1)
end=time.perf_counter()
time.sleep(1)
end2=time.perf_counter()
print(end2-start)
print(end-start)
(10)process_time,返回当前进程下,系统cpu计算时间,时间不包含sleep
start=time.process_time()
time.sleep(1)
end=time.process_time()
print(end-start)
(11) 将时间元组转换成字符串
按照时间的模板转换,格式化
t=time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S",t))
(12)将字符串转换成时间元组
time.strptime(string,指定的格式):按照指定的格式解析字符串,形成时间元组
print(time.strptime("2018-10-10 02:05:06","%Y-%m-%d %H:%M:%S"))
print(time.strptime("2018/10-10 02:05:06","%Y-%m-%d %H:%M:%S"))
2. datetime 日期包,年月日包
date 处理日期
time 处理时间
datetime 处理日期和时间
- date类,日期类型的对象
(1)构造器 __init__方法,需要参数年月日
from datetime import date
date(year,month,day)
print(date(2018,10,24))
<date 内存地址>
(2) 实例属性
d=date(2018,10,24)
print(d.year)
print(d.month)
print(d.day)
(3)类属性
print(date.max) 9999-12-31
print(date.min)
print(date.resolution) 两个date类型的对象的间隔
(4) 实例方法
d=date(2018,10,24)
ctime:返回特定格式的字符串来表示日期对象,返回值是字符串
print(d.ctime())
replace,返回新的date对象,按照repalce的参数
不是就地改变,是新创建时间对象进行替换
print(d.replace(year=2017))
print(d)
timetuple() 返回时间元组的对象,将当前的date类型的对象转换成时间元组
print(d.timetuple())
weekday():返回当前date类型日期的星期几(0-6)
print(d.weekday())
toordinal():返回当前date类型日期的时间序数
0001-01-01----1
print(d.toordinal())
d.strftime() 时间对象转换成字符串。
strd=d.strftime("%Y/%m/%d")
print(type(strd))
print(d.strftime("%Y/%m/%d"))
print(type(d))
(5)类方法
date.today()返回当前日期的日期对象
s=date.today()
print(date.today(),type(s))
根据传过来的时间序数,创建日期类型的对象
date.fromordinal(orinal)
print(date.fromordinal(1))
根据传过来的参数(时间戳 秒)创建创建时间对象
print(date.fromtimestamp(3600*24+1))
- time类
处理时间
(1)构造器 __init__
from datetime import time
print(time(3,4,5))
也可以传入微秒,有默认值
(2)实例属性
t=time(3,4,5)
print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond)
(3)类属性
print(time.min)
print(time.max)
print(time.resolution)
(4)实例方法
t=time(3,4,5)
t.replace()将时间对象中的hour minute second micorsecond 替换成参数的值
新创建time类型的对象
print(t.replace(minute=6))
print(t)
t.strftime()将时间类型的对象转换成字符串
print(t.strftime("%H*%M*%S"))
- datetime类
from datetime import datetime
(1) 构造器 __init__
dt=datetime(2018,10,24,16,4,55)
print(dt,type(dt))
(2)实例属性
print(dt.year)
print(dt.month)
print(dt.day)
print(dt.hour)
print(dt.minute)
print(dt.second)
print(dt.microsecond)
(3)实例方法
dt.ctime() 返回datetime对象的指定格式的时间,字符串
print(dt.ctime())
date() 返回date对象
d=dt.date()
print(d,type(d))
time() 返回time对象
t=dt.time()
print(t,type(t))
将datetime类型的对象属性进行替换,形成新的datetime类型对象
print(dt.replace(year=2017))
dt.timetuple() 将datetime类型的对象转换成时间元组
print(dt.timetuple())
weekday
print(dt.weekday())
strftime
print(dt.strftime("%Y/%m/%d %H:%M:%S"))
(4) 类属性
print(datetime.min)
print(datetime.max)
print(datetime.resolution)
(5)类方法
返回当前日期的年月日,时分秒
print(datetime.today())
print(datetime.now())
utc
print(datetime.utcnow())
datetime.fromordinal(o) 根据序数参数,转换成datetime类型的对象
print(datetime.fromordinal(1))
datetime.fromtimestamp() 根据时间戳,转换层datetime类型的对象
print(datetime.fromtimestamp(3600*24+1))
print(datetime.strptime("2018-10-24 16:17:55","%Y-%m-%d %H:%M:%S"))
import calendar
cal=calendar.month(2018,10)
print(cal)
“”"