zoukankan      html  css  js  c++  java
  • python-学习笔记之-Day5 双层装饰器 字符串格式化 python模块 递归 生成器 迭代器 序列化

    1.双层装饰器

    #!/usr/bin/env python

    # -*- coding: utf-8 -*-

    # author:zml

    LOGIN_INFO = False

    IS_ADMIN = False

     

    def check_log(func):

    def inner():

    res = func()

    if LOGIN_INFO:

    print('验证成功!')

    return res

    else:

    print('验证失败!')

    return inner

     

    def check_admin(func):

    def inner():

    res = func()

    if IS_ADMIN:

    print('欢迎管理员!')

    return res

    else:

    print('权限不足!')

    return inner

    @check_log

    @check_admin

    def login():

    inp = input('请输入您的用户名:')

    if inp == 'admin':

    global LOGIN_INFO

    global IS_ADMIN

    LOGIN_INFO = True

    IS_ADMIN = True

    else:

    print('正在尝试登录:{name}'.format(name=inp))

    login()

    clipboard

    双层装饰器,执行顺序是从上往下执行。返回顺序是和调用顺序相反的

    2.python模块

    python模块,类似其他语言中的类库,个人理解就是封装了很多函数的类。

    他能帮你完成常用功能,减少开发成本

    python模块分类

    自定义模块

    第三方模块

    内置模块

    1.自定义模块

    1.1定义模块

    clipboard[1]

    1.2其他文件导入模块

    clipboard[2]

    1.3执行结果

    clipboard[3]

    1.4python第三方模块安装方式

    1.pip安装

    2.源码包安装

    1.pip3 install 模块名

    clipboard[4]

    2.下载源码包,查看readme文件,安装模块

    python3 setup.py install

    2.1pytho模块导入方式

    import module(模块)                    导入整个模块

    from module.xx.xx import xx

    from 模块 import 模块方法                导入模块指定方法

    from module.xx.xx import xx as rename   导入模块指定方法,如果导入模块名称出现重名。可以重命名

    from module.xx.xx import *              导入模块的所有方法

    单模块建议使用import导入

    如果只使用模块中的某个特定的方法,建议使用from导入模块

    导入模块路径是根据sys模块下的path方法中存在的列表路径

    clipboard[5]

    如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append('路径') 添加。

    2.2python内置模块

    2.2.1sys模块

    sys.argv           命令行参数List,第一个元素是程序本身路径

    clipboard[6]

    sys.exit(n)        退出程序,正常退出时exit(0)

    sys.version        获取Python解释程序的版本信息

    clipboard[7]

    sys.maxint         最大的Int值python3已废弃

    sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

    clipboard[8]

    sys.platform       返回操作系统平台名称

    clipboard[9]

    sys.stdin          输入相关

    clipboard[10]

    sys.stdout         输出相关

    clipboard[11]

    sys.stderror       错误相关

    clipboard[12]

    2.2.2os模块

    os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径

    os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd

    clipboard[13]

    os.curdir                   返回当前目录: ('.')

    os.pardir                   获取当前目录的父目录字符串名:('..')

    os.makedirs('dir1/dir2')    可生成多层递归目录

    os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

    os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname

    os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

    os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

    os.remove()                 删除一个文件

    os.rename("oldname","new")  重命名文件/目录 当重命名文件存在是报错

    os.stat('path/filename')    获取文件/目录信息

    clipboard[14]

    os.sep                      操作系统特定的路径分隔符,win下为"\",Linux下为"/"

    clipboard[15]

    os.linesep                  当前平台使用的行终止符,win下为" ",Linux下为" "

    os.pathsep                  用于分割文件路径的字符串

    clipboard[16]

    os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'

    clipboard[17]

    os.system("bash command")   运行shell命令,直接显示。win可使用dos命令,linux使用shell

    clipboard[18]

    os.environ                  获取系统环境变量

    clipboard[19]

    os.path.abspath(path)       返回path规范化的绝对路径

    clipboard[20]

    os.path.split(path)         将path分割成目录和文件名二元组返回

    clipboard[21]

    os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素

    clipboard[22]

    os.path.basename(path)      返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即

    os.path.split(path)的第二个元素

    clipboard[23]

    os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False

    clipboard[24]

    os.path.isabs(path)         如果path是绝对路径,返回True

    clipboard[25]

    os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False

    clipboard[26]

     

    os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False

    clipboard[27]

    os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略

     

    os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间

    clipboard[28]

    os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间

    clipboard[29]

    3.字符串格式化

    Python的字符串格式化有两种方式: 百分号方式、format方式

    百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。[PEP-3101]

    This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator

    1、百分号方式

    %[(name)][flags][width].[precision]typecode

    • (name)      可选,用于选择指定的key
    • flags          可选,可供选择的值有:
      • +       右对齐;正数前加正好,负数前加负号;
      • -        左对齐;正数前无符号,负数前加负号;
      • 空格    右对齐;正数前加空格,负数前加负号;
      • 0        右对齐;正数前无符号,负数前加负号;用0填充空白处
    • width         可选,占有宽度
    • .precision   可选,小数点后保留的位数
    • typecode    必选
      • s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
      • r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
      • c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置
      • o,将整数转换成 八  进制表示,并将其格式化到指定位置
      • x,将整数转换成十六进制表示,并将其格式化到指定位置
      • d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
      • e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
      • E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
      • f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
      • F,同上
      • g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
      • G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
      • %,当字符串中存在格式化标志时,需要用 %%表示一个百分号

    注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式

    常用格式化:

    tpl = "i am %s" % "alex"

    tpl = "i am %s age %d" % ("alex", 18)

    tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}

    tpl = "percent %.2f" % 99.97623

    tpl = "i am %(pp).2f" % {"pp": 123.425556, }

    tpl = "i am %.2f %%" % {"pp": 123.425556, }

    2、Format方式

    [[fill]align][sign][#][0][width][,][.precision][type]

    • fill           【可选】空白处填充的字符
    • align        【可选】对齐方式(需配合width使用)
      • <,内容左对齐
      • >,内容右对齐(默认)
      • =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
      • ^,内容居中
    • sign         【可选】有无符号数字
      • +,正号加正,负号加负;
      • -,正号不变,负号加负;
      • 空格 ,正号空格,负号加负;
    • #            【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
    • ,            【可选】为数字添加分隔符,如:1,000,000
    • width       【可选】格式化位所占宽度
    • .precision 【可选】小数位保留精度
    • type         【可选】格式化类型
      • 传入” 字符串类型 “的参数
        • s,格式化字符串类型数据
        • 空白,未指定类型,则默认是None,同s
      • 传入“ 整数类型 ”的参数
        • b,将10进制整数自动转换成2进制表示然后格式化
        • c,将10进制整数自动转换为其对应的unicode字符
        • d,十进制整数
        • o,将10进制整数自动转换成8进制表示然后格式化;
        • x,将10进制整数自动转换成16进制表示然后格式化(小写x)
        • X,将10进制整数自动转换成16进制表示然后格式化(大写X)
      • 传入“ 浮点型或小数类型 ”的参数
        • e, 转换为科学计数法(小写e)表示,然后格式化;
        • E, 转换为科学计数法(大写E)表示,然后格式化;
        • f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
        • F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
        • g, 自动在e和f中切换
        • G, 自动在E和F中切换
        • %,显示百分比(默认显示小数点后6位)

    常用格式化:

    tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')

    tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])

    tpl = "i am {0}, age {1}, really {0}".format("seven", 18)

    tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])

    tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)

    tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})

    tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])

    tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)

    tpl = "i am {:s}, age {:d}".format(*["seven", 18])

    tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)

    tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})

    tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)

    tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)

    tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)

    tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

    更多格式化操作:https://docs.python.org/3/library/string.html

    4.生成器和迭代器

    迭代器

    迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退。另外,迭代器的一大优点是不要求事先准备好整个迭代过程中所有的元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的集合,比如几个G的文件

    特点:

    1. 访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
    2. 不能随机访问集合中的某个值 ,只能从头到尾依次访问
    3. 访问到一半时不能往回退
    4. 便于循环比较大的数据集合,节省内存

    生成一个迭代器:

    >>> a = iter([1,2,3,4,5])

    >>> a

    <list_iterator object at 0x101402630>

    >>> a.__next__()

    >>> a.__next__()

    >>> a.__next__()

    >>> a.__next__()

    >>> a.__next__()

    >>> a.__next__()

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    StopIteration

    生成器generator

    定义:一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator),如果函数中包含yield语法,那这个函数就会变成生成器

    代码:

    def cash_out(amount):

    while amount >0:

    amount -= 1

    yield 1<br>        print("擦,又来取钱了。。。败家子!")

    ATM = cash_out(5)

    print("取到钱 %s 万" % ATM.__next__())

    print("花掉花掉!")

    print("取到钱 %s 万" % ATM.__next__())

    print("取到钱 %s 万" % ATM.__next__())

    print("花掉花掉!")

    print("取到钱 %s 万" % ATM.__next__())

    print("取到钱 %s 万" % ATM.__next__())

    print("取到钱 %s 万" % ATM.__next__()) #到这时钱就取没了,再取就报错了

    print("取到钱 %s 万" % ATM.__next__())

    作用:

    这个yield的主要效果呢,就是可以使函数中断,并保存中断状态,中断后,代码可以继续往下执行,过一段时间还可以再重新调用这个函数,从上次yield的下一句开始执行。

    另外,还可通过yield实现在单线程的情况下实现并发运算的效果

    import time

    def consumer(name):

    print("%s 准备吃包子啦!" %name)

    while True:

    baozi = yield

    print("包子[%s]来了,被[%s]吃了!" %(baozi,name))

    def producer(name):

    c = consumer('A')

    c2 = consumer('B')

    c.__next__()

    c2.__next__()

    print("老子开始准备做包子啦!")

    for i in range(10):

    time.sleep(1)

    print("做了2个包子!")

    c.send(i)

    c2.send(i)

    producer("alex")

    5.递归

    特点

    递归算法是一种直接或者间接地调用自身算法的过程。在计算机编写程序中,递归算法对解决一大类问题是十分有效的,它往往使算法的描述简洁而且易于理解。

    递归算法解决问题的特点:

    (1) 递归就是在过程或函数里调用自身。

    (2) 在使用递归策略时,必须有一个明确的递归结束条件,称为递归出口。

    (3) 递归算法解题通常显得很简洁,但递归算法解题的运行效率较低。所以一般不提倡用递归算法设计程序。

    (4) 在递归调用的过程当中系统为每一层的返回点、局部量等开辟了栈来存储。递归次数过多容易造成栈溢出等。所以一般不提倡用递归算法设计程序。

    6.序列化

    Python中用于序列化的两个模块

    • json     用于【字符串】和 【python基本数据类型】 间进行转换
    • pickle   用于【python特有的类型】 和 【python基本数据类型】间进行转换

    Json模块提供了四个功能:dumps、dump、loads、load

    pickle模块提供了四个功能:dumps、dump、loads、load

    _5wbh]~un@%x

    clipboard[30]

    九、time

    时间相关的操作,时间有三种表示方式:

    • 时间戳               1970年1月1日之后的秒,即:time.time()
    • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
    • 结构化时间          元组包含了:年、日、星期等... time.struct_time    即:time.localtime()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    print time.time()
    print time.mktime(time.localtime())
      
    print time.gmtime()    #可加时间戳参数
    print time.localtime() #可加时间戳参数
    print time.strptime('2014-11-11''%Y-%m-%d')
      nt time.strftime('%Y-%m-%d'#默认当前时间
    print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间
    print time.asctime()
    print time.asctime(time.localtime())
    print time.ctime(time.time())
      
    import datetime
    '''
    datetime.date:表示日期的类。常用的属性有year, month, day
    datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
    datetime.datetime:表示日期时间
    datetime.timedelta:表示时间间隔,即两个时间点之间的长度
    timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
    strftime("%Y-%m-%d")
    '''
    import datetime
    print datetime.datetime.now()
    print datetime.datetime.now() - datetime.timedelta(days=5)

    logging模块  

    很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()info()warning()error() and critical() 5个级别,下面我们看一下怎么用。

    最简单用法

    1
    2
    3
    4
    5
    6
    7
    8
    import logging
     
    logging.warning("user [alex] attempted wrong password more than 3 times")
    logging.critical("server is down")
     
    #输出
    WARNING:root:user [alex] attempted wrong password more than 3 times
    CRITICAL:root:server is down

    看一下这几个日志级别分别代表什么意思

    LevelWhen it’s used
    DEBUG Detailed information, typically of interest only when diagnosing problems.
    INFO Confirmation that things are working as expected.
    WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
    ERROR Due to a more serious problem, the software has not been able to perform some function.
    CRITICAL A serious error, indicating that the program itself may be unable to continue running.

      

    如果想把日志写到文件里,也很简单

    1
    2
    3
    4
    5
    6
    import logging
     
    logging.basicConfig(filename='example.log',level=logging.INFO)
    logging.debug('This message should go to the log file')
    logging.info('So should this')
    logging.warning('And this, too')

    其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。

    1
    logging.basicConfig(filename='example.log',level=logging.INFO)

    感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!

    1
    2
    3
    4
    5
    6
    import logging
    logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    logging.warning('is when this event was logged.')
     
    #输出
    12/12/2010 11:46:36 AM is when this event was logged.

      

    如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了

    The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

    • Loggers expose the interface that application code directly uses.
    • Handlers send the log records (created by loggers) to the appropriate destination.
    • Filters provide a finer grained facility for determining which log records to output.
    • Formatters specify the layout of log records in the final output.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    import logging
     
    #create logger
    logger = logging.getLogger('TEST-LOG')
    logger.setLevel(logging.DEBUG)
     
     
    # create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
     
    # create file handler and set level to warning
    fh = logging.FileHandler("access.log")
    fh.setLevel(logging.WARNING)
    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
     
    # add formatter to ch and fh
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
     
    # add ch and fh to logger
    logger.addHandler(ch)
    logger.addHandler(fh)
     
    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    2016-06-14 23:13:36,345 - TEST-LOG - DEBUG - debug message
    2016-06-14 23:13:36,348 - TEST-LOG - INFO - info message
    2016-06-14 23:13:36,348 - TEST-LOG - WARNING - warn message
    2016-06-14 23:13:36,348 - TEST-LOG - ERROR - error message
    2016-06-14 23:13:36,348 - TEST-LOG - CRITICAL - critical message
  • 相关阅读:
    江西师范大学瑶湖校区图片
    什么是sp?
    教育技术学硕士点学校排名
    西南师大教育技术学专业2005年入学考试信息
    什么是"工包"?
    买书网址
    2006年全国教育技术学专业新增硕士点
    今天终于拿到书了
    2007年教育学专业基础综合考试大纲(重要部分) ——下载地址
    电脑DIY推荐
  • 原文地址:https://www.cnblogs.com/zhanmeiliang/p/5568458.html
Copyright © 2011-2022 走看看