1.自定义模块(变量,函数,类) 2.系统模块
导入模块
import xxx
xxx.methon()
from xxx import 函数,变量,类
from xxx import *
函数名()
result=变量
c=类名(参数)
c.函数()
限制模块内容获取
__all__=[*可以访问全部]
无论import还是from形式,都会将模块内容进行加载
如需不进行调用,使用
if __name__ == '__main__':
包
********************************
文件夹 非.py文件 包 .py文件
导入
from 包名.模块名 import 函数,变量,类
__init__.py文件
1.导入包时,默认调用
2.只需通过包名,函数访问
3。结合__all__=[]限制模块访问
//循环导入(架构不当,模块相互导入)
Module a
def a():
b()
def b():
a()
Module b
避免方法:
1.重构
2.将导入语句放入函数体
3.把导入语句放到模块最后
系统模块:
sys:sys.path(Sources Root) sys.version sys.argv
- time 时间戳
※time.sleep()睡眠
※t=time.time()
time.ctime(t) //时间戳转字串符
time.localtime(t) //时间戳-->元组
time.mktime(t) //元组-->时间戳
※time.strftime('%Y-%m-%d %H:%M:%S') //元组-->字串符
time.strptime('2019-01-01','%Y-%m-%d') //字串符-->元组
- datetime
datetime.data.today() //今天
now=datetime.datetime.now() //当前日期时间
timedel=datetime.timedelta(hours=2) //时间差(应用:缓存Redis,会话Session)
result=now+timedel
- random
randint(x,x)
choice(list) //随机选择列表内容
shuffle(list) //洗牌,打乱列表顺序
//随机生成验证码
import random
def ranvcode(n):
code = ''
for i in range(n):
r1 = str(random.randint(0, 9)) # 数字
r2 = chr(random.randint(65, 90)) # 大写
r3 = chr(random.randint(97, 122)) # 小写
r = random.choice([r1, r2, r3])
code += r
return code
code=ranvcode(5)
print(code)
- 转换
chr :Unicode--str
ord :str-->Unicode
ord-->chr-->str
- 加密算法 hashlib
哈希 md5(32) sha1(40) sha256(64)
base64
import hashlib
plaintext='secret'
md5=hashlib.md5(plaintext.encode('utf-8'))
ciphertext=md5.hexdigest()
print(ciphertext)
- 第三方模块
1.console:
pip install xxx
2.pycharm:install