前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python day five

python day five

作者头像
py3study
发布2020-01-13 16:40:39
发布2020-01-13 16:40:39
63600
代码可运行
举报
文章被收录于专栏:python3python3
运行总次数:0
代码可运行
代码语言:javascript
代码运行次数:0
运行
复制
一、双层装饰器

def w1(func):    def inner(*args,**kwargs):        # 验证1        # 验证2        # 验证3        return func(*args,**kwargs)    return innerdef w2(func):    def inner(*args,**kwargs):        # 验证1        # 验证2        # 验证3        return func(*args,**kwargs)    return inner@w1@w2def f1(arg1,arg2,arg3):    print ('f1')

代码语言:javascript
代码运行次数:0
运行
复制
二、python字符串格式化:百分号

%[(name)][flags][width].[precision]typecode例:s1 = 'my name is %s,age is %d' %('yang',22)#%s 和%d 都是占位符;1、(name) 可选;根据名字指定key 进行格式化   例:s = 'my name is %(name)s, age is %(age)d ' %{'name':'yang','age':22}2、flags  可选;左对齐和右对齐     +      右对齐;正数前加正好,负数前加负号;   -      左对齐;正数前无符号,负数前加负号;   空格   右对齐;正数前加空格,负数前加负号;   0      右对齐;正数前无符号,负数前加负号;用0填充空白处  例:s = 'my name is%(name)+10s age is%(age)d bbb ' %{'name':'yang','age':22}3、width  可选;占有宽度4、.precision 可选;小数点后保留的位数    例:s = 'my name is %(name)s, age is %(age).2f ' %{'name':'yang','age':22.12345}5、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;)   % (1.当没有占位符的时候,1个%输出1个%;2.当有占位符的时候,2个%输出1个%)

代码语言:javascript
代码运行次数:0
运行
复制
三、python字符串格式化:format

[[fill]align][sign][#][0][width][,][.precision][type]fill   【可选】空白处填充的字符align  【可选】对齐方式(需配合width使用)          <,内容左对齐          >,内容右对齐(默认)          =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字          ^,内容居中sign   【可选】有无符号数字          +,正号加正,负号加负;            -,正号不变,负号加负;          空格 ,正号空格,负号加负;#       【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示,      【可选】为数字添加分隔符,如:1,000,000width  【可选】格式化位所占宽度.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

代码语言:javascript
代码运行次数:0
运行
复制
四、生成器

生成器:使用函数创造出来的;普通函数中出现yield就叫做生成器(generator)(有生成能力)。def func():    print('start')    yield 1    yield 2ret = func()print(ret)#输出:<generator object func at 0x0000000002709F30>      #生成器的结果例1:#生成器例子li = [11,22,33,44]result = filter(lambda x: x>22,li)print(result)     #具有生成指定条件数据的能力的一个对象(当循环的时候生成)#python3.0 不直接显示结果,如果全部打印出来,会占用内存空间。#python2.0 直接显示结果#输出:<filter object at 0x0000000002A34160>        #生成器的结果#例2:def func():    print('111')    yield 1    print('222')    yield 2ret = func()r1 = ret.__next__()print(r1)r2 = ret.__next__()print(r2)'''#输出   111   1   222   2'''#例3:基于生成器实现xrange功能;(python2.7有这个功能)def myrange(arg):    start = 0    while True:        if start > arg:            return        yield start        start += 1ret = myrange(2)r = ret.__next__()print(r)r1 = ret.__next__()print(r1)r2 = ret.__next__()print(r2)'''输出:    0    1    2'''

代码语言:javascript
代码运行次数:0
运行
复制
五、迭代器

迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退。另外,迭代器的一大优点是不要求事先准备好整个迭代过程中所有的元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的集合,比如几个G的文件  特点:      1.访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容     2.不能随机访问集合中的某个值 ,只能从头到尾依次访问     3.访问到一半时不能往回退     4.便于循环比较大的数据集合,节省内存

代码语言:javascript
代码运行次数:0
运行
复制
六、函数递归

#本质是一个函数调用另一个函数#自己调用自己;类似写了一个循环#例如:def func(n):    n+=1    if n>=4:        return 'end'    return func(n)r = func(0)print (r)#输出:end

代码语言:javascript
代码运行次数:0
运行
复制
七、python模块介绍

python 模块介绍(其他语言叫做类库)#内置模块例子import sysprint (sys.argv)#执行python a.py 123 456#输出:['a.py','123','456']1.分类:    内置模块    自定义模块    第三方模块2.使用模块:    先导入    后使用3.模块存在的方式:    一个.py文件    一个文件夹,由多个.py文件组成一个模块4.为什么要有模块?    将代码归类5.导入模块的依据(查找python的内置目录)    注意:当python执行的时候,先找当前所在目录,再找内置目录    import sys    sys.path    for item in sys.path:        print (item)    #往内置目录里添加目录:sys.path.append('E:\\')6.模块名称的重要性    自定义模块的时候,注意不要和内置的模块重名。    当重名之后,python优先执行当前所在目录7.导入模块方式    1.import 模块名    2.from 模块名 import 函数名(可以换成* 代表所有函数)(一般不这么写)    什么情况用什么导入方式:        1.单模块,同一目录的时候            用import 模块名        2.在别的文件夹下的时候            用from 文件夹名 import 模块名        3.导入多个文件夹,模块名一样的时候            from aa import cc as aa.cc #别名            from bb import cc as bb.cc

代码语言:javascript
代码运行次数:0
运行
复制
八、安装第三方模块

1.pip3 安装      pip3 install 模块名(如:requests)2.源码安装      下载,解压,进入目录,python3 setup.py install

代码语言:javascript
代码运行次数:0
运行
复制
九、python序列化json

#序列化: 将python数据类型转换成字符串#例1:import jsondic = {'k1':'v1'}result = json.dumps(dic)        #序列化print(result,type(result))#反序列化:将字符串转换成python基本数据类型#例2:s1 = '{"k1":"v1"}'            #必须为双引号result1 = json.loads(s1)        #反序列化print(result1,type(result1))#例:基于天气API获取天气相关的json参数import requestsimport jsonresponse = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=北京')response.encoding = 'utf-8'dic = json.loads(response.text)  #反序列化print(dic)print(type(dic))                 #输出dict#例3 json.dump()     #两个步骤1、先序列化 2、后写入文件#例4 json.load()     #两个步骤1、先读取文件内容到内存 2、再序列化

代码语言:javascript
代码运行次数:0
运行
复制
十、python序列化pickle

#python序列化之pickle#序列化:将python数据类型转换成字符串import pickleli = [11,22,33,44]r1 = pickle._dumps(li)      #序列化print (r1)print (type(r1))r2 = pickle.loads(r1)       #反序列化print (r2)print (type(r2))'''输出:    b'\x80\x03]q\x00(K\x0bK\x16K!K,e.'    <class 'bytes'>    [11, 22, 33, 44]    <class 'list'>'''#同样dump和load和json的一样

代码语言:javascript
代码运行次数:0
运行
复制
十一、python序列化json和pickle的区别

json:    1.适合跨语言使用    2.只能对python基本数据类型做操作    pickle:    1.仅适用于python    2.可以对python所有数据类型做操作

代码语言:javascript
代码运行次数:0
运行
复制
十二、python时间处理模块time 和 datetime

import time import datetime   print(time.clock()) #返回处理器时间,3.3开始已废弃 print(time.process_time()) #返回处理器时间,3.3开始已废弃 print(time.time()) #返回当前系统时间戳 print(time.ctime()) #输出Tue Jan 26 18:23:48 2016 ,当前系统时间 print(time.ctime(time.time()-86640)) #将时间戳转为字符串格式 print(time.gmtime(time.time()-86640)) #将时间戳转换成struct_time格式 print(time.localtime(time.time()-86640)) #将时间戳转换成struct_time格式,但返回 的本地时间 print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式 #time.sleep(4) #sleep print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式 print(time.strptime("2016-01-28","%Y-%m-%d") ) #将字符串格式转换成struct_time格式   #datetime module   print(datetime.date.today()) #输出格式 2016-01-26 print(datetime.date.fromtimestamp(time.time()-864400) ) #2016-01-16 将时间戳转成日期格式 current_time = datetime.datetime.now() # print(current_time) #输出2016-01-26 19:04:30.335935 print(current_time.timetuple()) #返回struct_time格式   #datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) print(current_time.replace(2014,9,12)) #输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换   str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #将字符串转换成日期格式 new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比现在加10天 new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比现在减10天 new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比现在减10小时 new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比现在+120s print(new_date)

代码语言:javascript
代码运行次数:0
运行
复制
十三、python日志处理模块logging

#简单写法:import logginglogging.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 timesCRITICAL:root:server is down'''#日志级别'''Level    When it’s usedDEBUG    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.'''#把日志写到文件里:import logginglogging.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的日志,那把日志级别改成DEBUG就行了。#日志加上时间:import logginglogging.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.例如:import logging#create loggerlogger = logging.getLogger('TEST-LOG')logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create file handler and set level to warningfh = logging.FileHandler("access.log")fh.setLevel(logging.WARNING)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to ch and fhch.setFormatter(formatter)fh.setFormatter(formatter)# add ch and fh to loggerlogger.addHandler(ch)logger.addHandler(fh)# 'application' codelogger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档