4月8日 python学习总结 模块与包

一、包

#官网解释
Packages are a way of structuring Python’s module namespace by using “dotted module names”
包是一种通过使用‘.模块名’来组织python模块名称空间的方式。

#具体的:包就是一个包含有__init__.py文件的文件夹,所以其实我们创建包的目的就是为了用文件夹将文件/模块组织起来

#需要强调的是:
  1. 在python3中,即使包下没有__init__.py文件,import 包仍然不会报错,而在python2中,包下一定要有该文件,否则import 包报错

  2. 创建包的目的不是为了运行,而是被导入使用,记住,包只是模块的一种形式而已,包的本质就是一种模块

注意:

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

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

#3、包A和包B下有同名模块也不会冲突,如A.a与B.a来自俩个命名空间

3、包的使用之from ... import ...

   需要注意的是from后import导入的模块,必须是明确的一个不能带点,否则会有语法错误,如:from a import b.c是错误语法

1、在导入时带点的,点的左边的必须是一个包,这是导入包的特有语法

2、包内模块之间的直接导入应使用 from ... import ...

3、import 之后必须是一个明确的名字,没有任何前缀

4、相对路径和绝对路径

我们的最顶级包glance是写给别人用的,然后在glance包内部也会有彼此之间互相导入的需求,这时候就有绝对导入和相对导入两种方式:

绝对导入:以glance作为起始

相对导入:用.或者..的方式最为起始(只能在一个包中使用,不能用于不同目录内)

例如:我们在glance/api/version.py中想要导入glance/cmd/manage.py

1 在glance/api/version.py
2 
3 #绝对导入
4 from glance.cmd import manage
5 manage.main()
6 
7 #相对导入
8 from ..cmd import manage
9 manage.main()

  

 

 

 

 

二、模块

1、time模块

在Python中,通常有这几种方式来表示时间:

  • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
  • 格式化的时间字符串(Format String)
  • 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
    import time
    #--------------------------我们先以当前时间为准,让大家快速认识三种形式的时间
    print(time.time()) # 时间戳:1487130156.419527
    print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:'2017-02-15 11:40:53'
    
    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.
    
    格式化字符串的时间格式
    

     

    #--------------------------按图1转换时间
    # localtime([secs])
    # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
    time.localtime()
    time.localtime(1473525444.037215)
    
    # gmtime([secs]) 和localtime()方法类似,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"。
    

      

2、datetime模块

#时间加减
import datetime

# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
#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模块

  

3、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) #打乱item的顺序,相当于"洗牌"
print(item)

  随机生成验证码

import random
def make_code(n):
    res=''
    for i in range(n):
        s1=chr(random.randint(65,90))
        s2=str(random.randint(0,9))
        res+=random.choice([s1,s2])
    return res

print(make_code(9))

生成随机验证码

  

4、sys模块

1 sys.argv           命令行参数List,第一个元素是程序本身路径
2 sys.exit(n)        退出程序,正常退出时exit(0)
3 sys.version        获取Python解释程序的版本信息
4 sys.maxint         最大的Int值
5 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
6 sys.platform       返回操作系统平台名称

打印进度条

#=========知识储备==========
#进度条的效果
[#             ]
[##            ]
[###           ]
[####          ]

#指定宽度
print('[%-15s]' %'#')
print('[%-15s]' %'##')
print('[%-15s]' %'###')
print('[%-15s]' %'####')

#打印%
print('%s%%' %(100)) #第二个%号代表取消第一个%的特殊意义

#可传参来控制宽度
print('[%%-%ds]' %50) #[%-50s]
print(('[%%-%ds]' %50) %'#')
print(('[%%-%ds]' %50) %'##')
print(('[%%-%ds]' %50) %'###')


#=========实现打印进度条函数==========
import sys
import time

def progress(percent,width=50):
    if percent >= 1:
        percent=1
    show_str=('[%%-%ds]' %width) %(int(width*percent)*'#')
    print('
%s %d%%' %(show_str,int(100*percent)),file=sys.stdout,flush=True,end='')


#=========应用==========
data_size=1025
recv_size=0
while recv_size < data_size:
    time.sleep(0.1) #模拟数据的传输延迟
    recv_size+=1024 #每次收1024

    percent=recv_size/data_size #接收的比例
    progress(percent,width=70) #进度条的宽度70

打印进度条

  

 作业:

  

4.5号作业
    1、复习常用模块time、datetime、random、os、sys、shutil、json、pickle、logging编写博客
    2、编写认证功能装饰器,同一用户输错三次密码则锁定5分钟,5分钟内无法再次登录
    3、编写注册功能,用户输入用户名、性别、年龄、密码。。。还需要输入一个随机验证码,若用户在60秒内输入验证码错误
    则产生新的验证码要求用户重新输入,直至输入正确,则将用户输入的信息以json的形式存入文件
    4、编写进度条功能
        import random
        import time
        def pri_Progress(pro):
            w=60
            figure=('[%%-%ds]'%w)%('#'*int(60*pro))
            pro=100*pro
            print('
%s %d%%'%(figure,pro),end=' ')

        data_size = 1025
        load_size = 0
        while not load_size>data_size:
            pro=load_size/data_size
            time.sleep(0.1)
            pri_Progress(pro)
            num=random.randint(20,50)
            load_size+=num
            if load_size>data_size:
                load_size=data_size



    5、明日默写:生成随机验证码功能、打印进度条功能        
        #产生一个随机验证码
        def ver_code(n):
            l=''
            for i in range(n):
                s1=chr(random.randint(65,90))
                s2 = chr(random.randint(97,122))
                s3=random.randint(0,9)
                code=random.choice([s1,s2,s3])
                l=l+str(code)
            return l
        print(ver_code(4))
原文地址:https://www.cnblogs.com/95lyj/p/8745572.html