python day13

一、循环导入

模块循环/嵌套导入抛出异常的根本原因是由于在python中模块被导入一次之后,就不会重新导入,只会在第一次导入时执行模块内代码。项目中应该尽量避免出现循环/嵌套导入,如果出现多个模块都需要共享的数据,可以将共享的数据集中存放到某一个地方

解决循环导入的两种方案

1.数据被导入过了,不会重新导入。再次导入模块时,数据没有存在模块中。此时须将导入语句放到最后。

2.执行文件并不等于导入文件。此时须将导入语句放到函数中

二、包:含有__init__.py的文件夹

1.创建包的目的:被导入使用

随着功能增多,我们需要用模块去组织功能,而随着模块越来越多,我们需要用包将模块文件组织起来,来提高程序的结构性和可维护性

2.注意:

1)关于包相关的导入语句也分为import和from...import...,无论在什么位置,在导入时都必须遵守一个原则:凡是在导入时带点的,左边都必须是一个包(即包名. )否则非法。如item,subitem,subsubitem,但都必须遵循这个原则。但对于导入后,在使用时就没有这种限制了,点的左边可以是包,模块,函数,类(它们都可以用点的方式调用自己的属性)。

2)import导入文件时,产生名称空间中的名字来源于文件,import 包,产生的名称空间的名字同样来源于文件,即包下的__init__.py,导入包本质就是在导入该文件

3)包A和包B下有同名模块也不会冲突

3.绝对导入和相对导入

绝对导入:以执行文件的sys.path为起点开始导入

优:执行文件与被导入的模块中都可以使用

缺:所有导入都是以sys.path为起点,导入麻烦

相对导入:参照当前文件所在的文件夹为起始开始查找

优:导入更简单

缺:只能在导入包中模块时才能使用

.代表当前所在文件的文件夹,..代表上一级文件夹,...代表上一级的上一级文件夹

注意:1.相对导入只能用于包内部模块之间的相互导入,导入者与被导入者都必须存在于一个包中

          2.attempted relative import beyond top-level package # 试图在顶级包之外使用相对导入是错误的,即必须在顶级包内使用相对导入,每增加一个.代表跳到上一级文件夹,而上一级不应该超出顶级包

三、json和pickle------->解决序列化问题

1.序列化:将内存中数据类型转成另一种格式

2.为什么要序列化

I.持久保存程序运行状态

II.数据的跨平台性

3.如何序列化

json:表示出一个字符串,可以被所有语言读取

import json

dict1 = {"name": '张'}
js_dict1=json.dumps(dict1)
with open('dict1.json','wt',encoding='utf8') as f:
    f.write(js_dict1)

with open('dict1.json','rt',encoding='utf8') as f1:
    res=f1.read()
    dict1=json.loads(res)
    print(type(dict1))  # <class 'dict'>

# 方法2
with open('dict1.json','wt',encoding='utf8') as f:
    json.dump(dict1,f)

with open('dict1.json','rt',encoding='utf8') as f1:
    dict2=json.load(f1)
    print(dict2)

  优:其为通用格式,所有编程语言都可识别,跨平台性好

       缺:不能识别所有python类型(如' ',其全为" ")

pickle:表现出二进制代码

import pickle

with open('dict1.picke','wb',) as f:
    pickle.dump(dict1,f)

with open('dict1.picke','rb',) as f2:
    dict2=pickle.load(f2)
    print(dict2)
# ----------------------
dict1_p = pickle.dumps(dict1)
with open('dict1.pkl', 'wb', ) as f:
    f.write(dict1_p)

with open('dict1.pkl', 'rb', ) as f1:
    dict2 = pickle.loads(f1.read())
print(dict2)

  

优:可识别所有python类型

缺:只能被python识别(可序列化set类型)

四、time和data time模块

time时间戳(timestamp):表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。

格式化的时间字符串(Format String)

结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)

格式化的时间字符  提供时间和自定义格式

 sleep(secs)  # 线程推迟指定的时间运行,单位为秒。

import time
print(time.time())  # 时间戳
print(time.strftime("%Y-%m-%d %X")) #格式化时间
print(time.localtime()) #本地时区的struct_time
print(time.gmtime())    #UTC时区的struct_time

  

%a    Locale’s abbreviated weekday name.     
%A    Locale’s full weekday name.     
%b    Locale’s abbreviated month name.     
%B    Locale’s full month name.     
%c    Locale’s appropriate date and time representation.     
%d    Day of the month as a decimal number [01,31].     
%H    Hour (24-hour clock) as a decimal number [00,23].     
%I    Hour (12-hour clock) as a decimal number [01,12].     
%j    Day of the year as a decimal number [001,366].     
%m    Month as a decimal number [01,12].     
%M    Minute as a decimal number [00,59].     
%p    Locale’s equivalent of either AM or PM.    (1)
%S    Second as a decimal number [00,61].    (2)
%U    Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)
%w    Weekday as a decimal number [0(Sunday),6].     
%W    Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)
%x    Locale’s appropriate date representation.     
%X    Locale’s appropriate time representation.     
%y    Year without century as a decimal number [00,99].     
%Y    Year with century as a decimal number.     
%z    Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].     
%Z    Time zone name (no characters if no time zone exists).     
%%    A literal '%' character.

格式化字符串的时间格式

 格式化字符串的时间格式

                               

#--------------------------按上图转换时间
# localtime([secs])
# 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
time.localtime()
time.localtime(1473525444.037215)
#gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。

# mktime(t) : 将一个struct_time转化为时间戳。
print(time.mktime(time.localtime()))#1473525749.0

# strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
# time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
# 元素越界,ValueError的错误将会被抛出。
print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56

# time.strptime(string[, format])
# 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
#time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
#  tm_wday=3, tm_yday=125, tm_isdst=-1)
#在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。

  data time

import datetime

# print(datetime.datetime.now()) 
#print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分


#
# c_time  = datetime.datetime.now()
# print(c_time.replace(minute=3,hour=2)) #时间替换

datetime模块

五 random模块:用来生产随机量

import random
 
print(random.random())#(0,1)----float    大于0且小于1之间的小数
 
print(random.randint(1,3))  #[1,3]    大于等于1且小于等于3之间的整数
 
print(random.randrange(1,3)) #[1,3)    大于等于1且小于3之间的整数
 
print(random.choice([1,'23',[4,5]]))#1或者23或者[4,5]
 
print(random.sample([1,'23',[4,5]],2))#列表元素任意2个组合
 
print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716 
 
 
item=[1,3,5,7,9]
random.shuffle(item) #打乱顺序
print(item)
import random
def code(num=4):
    str1 = ""
    for i in range(num):
        digit0 = str(random.randint(0, 9))  # 生成数字
        alpha0 = chr(random.randint(65, 90))  # 生成字母
        str0 = random.choice([digit0, alpha0])
        str1 += str0
    return str1

print(code(8))
# DU20302K

用random写一个可以生成指定位数验证码的功能,验证码由大写字母和数字组成。

  

原文地址:https://www.cnblogs.com/zhouyuquan/p/10076848.html