Python重点知识汇总,建议收藏
文章标签:
html 转义
Py2 VS Py3
- print成为了函数,python2是关键字
- 不再有unicode对象,默认str就是unicode
- python3除号返回浮点数
- 没有了long类型
- xrange不存在,range替代了xrange
- 可以使用中文定义函数名变量名
- 高级解包 和*解包
- 限定关键字参数 *后的变量必须加入名字=值
- raise from
- iteritems移除变成items()
- yield from 链接的生成器
- asyncio,async/await原生协程支持异步编程
- 新增 enum, mock, ipaddress, concurrent.futures, asyncio urllib, selector
- 不同分类间不能进行比较
- 同一枚举类间只能进行相等的比较
- 枚举类的使用(编号默认从1开始)
- 为了避免枚举类中相同枚举值得出现,可以使用@unique装饰枚举类
#枚举的注意事项
from enum import Enum
class COLOR(Enum):
YELLOW=1
#YELLOW=2#会报错
GREEN=1#不会报错,GREEN可以看作是YELLOW的别名
BLACK=3
RED=4
print(COLOR.GREEN)#COLOR.YELLOW,还是会打印出YELLOW
for i in COLOR:#遍历一下COLOR并不会有GREEN
print(i)
#COLOR.YELLOW\nCOLOR.BLACK\nCOLOR.RED\n怎么把别名遍历出来
for i in COLOR.__members__.items():
print(i)
# output:('YELLOW', <COLOR.YELLOW: 1>)\n('GREEN', <COLOR.YELLOW: 1>)\n('BLACK', <COLOR.BLACK: 3>)\n('RED', <COLOR.RED: 4>)
for i in COLOR.__members__:
print(i)
# output:YELLOW\nGREEN\nBLACK\nRED
#枚举转换
#最好在数据库存取使用枚举的数值而不是使用标签名字字符串
#在代码里面使用枚举类
a=1
print(COLOR(a))# output:COLOR.YELLOW
py2/3 转换工具
- six模块:兼容pyton2和pyton3的模块
- 2to3工具:改变代码语法版本
- __future__:使用下一版本的功能
常用的库
- 必须知道的collections
- https://segmentfault.com/a/1190000017385799
- python排序操作及heapq模块
- https://segmentfault.com/a/1190000017383322
- itertools模块超实用方法
- https://segmentfault.com/a/1190000017416590
不常用但很重要的库存
- dis(代码字节码分析)
- inspect(生成器状态)
- cProfile(性能分析)
- bisect(维护有序列表)
- fnmatch
- fnmatch(string,"*.txt") #win下不区分大小写
- fnmatch根据系统决定
- fnmatchcase完全区分大小写
- timeit(代码执行时间)
def isLen(strString):
#还是应该使用三元表达式,更快
return True if len(strString)>6 else False
def isLen1(strString):
#这里注意false和true的位置
return [False,True][len(strString)>6]
import timeit
print(timeit.timeit('isLen1("5fsdfsdfsaf")',setup="from __main__ import isLen1"))
print(timeit.timeit('isLen("5fsdfsdfsaf")',setup="from __main__ import isLen"))
- contextlib
- @contextlib.contextmanager使生成器函数变成一个上下文管理器
- types(包含了标准解释器定义的所有类型的类型对象,可以将生成器函数修饰为异步模式)
import types
types.coroutine #相当于实现了__await__
- html(实现对html的转义)
import html
html.escape("<h1>I'm Jim</h1>") # output:'<h1>I'm Jim</h1>'
html.unescape('<h1>I'm Jim</h1>') # <h1>I'm Jim</h1>
- mock(解决测试依赖)
- concurrent(创建进程池和线程池)
from concurrent.futures import ThreadPoolExecutor
pool = ThreadPoolExecutor()
task = pool.submit(函数名,(参数)) #此方法不会阻塞,会立即返回
task.done()#查看任务执行是否完成
task.result()#阻塞的方法,查看任务返回值
task.cancel()#取消未执行的任务,返回True或False,取消成功返回True
task.add_done_callback()#回调函数
task.running()#是否正在执行 task就是一个Future对象
for data in pool.map(函数,参数列表):#返回已经完成的任务结果列表,根据参数顺序执行
print(返回任务完成得执行结果data)
from concurrent.futures import as_completed
as_completed(任务列表)#返回已经完成的任务列表,完成一个执行一个
wait(任务列表,return_when=条件)#根据条件进行阻塞主线程,有四个条件
- selector(封装select,用户多路复用io编程)
- asyncio
future=asyncio.ensure_future(协程) 等于后面的方式 future=loop.create_task(协程)
future.add_done_callback()添加一个完成后的回调函数
loop.run_until_complete(future)
future.result()查看写成返回结果
asyncio.wait()接受一个可迭代的协程对象
asynicio.gather(*可迭代对象,*可迭代对象) 两者结果相同,但gather可以批量取消,gather对象.cancel()
一个线程中只有一个loop
在loop.stop时一定要loop.run_forever()否则会报错
loop.run_forever()可以执行非协程
最后执行finally模块中 loop.close()
asyncio.Task.all_tasks()拿到所有任务 然后依次迭代并使用任务.cancel()取消
偏函数partial(函数,参数)把函数包装成另一个函数名 其参数必须放在定义函数的前面
loop.call_soon(函数,参数)
call_soon_threadsafe()线程安全
loop.call_later(时间,函数,参数)
在同一代码块中call_soon优先执行,然后多个later根据时间的升序进行执行
如果非要运行有阻塞的代码
使用loop.run_in_executor(executor,函数,参数)包装成一个多线程,然后放入到一个task列表中,通过wait(task列表)来运行
通过asyncio实现http
reader,writer=await asyncio.open_connection(host,port)
writer.writer()发送请求
async for data in reader:
data=data.decode("utf-8")
list.append(data)
然后list中存储的就是html
as_completed(tasks)完成一个返回一个,返回的是一个可迭代对象
协程锁
async with Lock():
Python进阶
- 进程间通信:
- Manager(内置了好多数据结构,可以实现多进程间内存共享)
from multiprocessing import Manager,Process
def add_data(p_dict, key, value):
p_dict[key] = value
if __name__ == "__main__":
progress_dict = Manager().dict()
from queue import PriorityQueue
first_progress = Process(target=add_data, args=(progress_dict, "bobby1", 22))
second_progress = Process(target=add_data, args=(progress_dict, "bobby2", 23))
first_progress.start()
second_progress.start()
first_progress.join()
second_progress.join()
print(progress_dict)
- Pipe(适用于两个进程)
from multiprocessing import Pipe,Process
#pipe的性能高于queue
def producer(pipe):
pipe.send("bobby")
def consumer(pipe):
print(pipe.recv())
if __name__ == "__main__":
recevie_pipe, send_pipe = Pipe()
#pipe只能适用于两个进程
my_producer= Process(target=producer, args=(send_pipe, ))
my_consumer = Process(target=consumer, args=(recevie_pipe,))
my_producer.start()
my_consumer.start()
my_producer.join()
my_consumer.join()
- Queue(不能用于进程池,进程池间通信需要使用Manager().Queue())
from multiprocessing import Queue,Process
def producer(queue):
queue.put("a")
time.sleep(2)
def consumer(queue):
time.sleep(2)
data = queue.get()
print(data)
if __name__ == "__main__":
queue = Queue(10)
my_producer = Process(target=producer, args=(queue,))
my_consumer = Process(target=consumer, args=(queue,))
my_producer.start()
my_consumer.start()
my_producer.join()
my_consumer.join()
- 进程池
def producer(queue):
queue.put("a")
time.sleep(2)
def consumer(queue):
time.sleep(2)
data = queue.get()
print(data)
if __name__ == "__main__":
queue = Manager().Queue(10)
pool = Pool(2)
pool.apply_async(producer, args=(queue,))
pool.apply_async(consumer, args=(queue,))
pool.close()
pool.join()
- sys模块几个常用方法
- argv 命令行参数list,第一个是程序本身的路径
- path 返回模块的搜索路径
- modules.keys() 返回已经导入的所有模块的列表
- exit(0) 退出程序
- a in s or b in s or c in s简写
- 采用any方式:all() 对于任何可迭代对象为空都会返回True
# 方法一
True in [i in s for i in [a,b,c]]
# 方法二
any(i in s for i in [a,b,c])
# 方法三
list(filter(lambda x:x in s,[a,b,c]))
- set集合运用
- {1,2}.issubset({1,2,3})#判断是否是其子集
- {1,2,3}.issuperset({1,2})
- {}.isdisjoint({})#判断两个set交集是否为空,是空集则为True
- 代码中中文匹配
- [u4E00-u9FA5]匹配中文文字区间[一到龥]
- 查看系统默认编码格式
import sys
sys.getdefaultencoding() # setdefaultencodeing()设置系统编码方式
- getattr VS getattribute
class A(dict):
def __getattr__(self,value):#当访问属性不存在的时候返回
return 2
def __getattribute__(self,item):#屏蔽所有的元素访问
return item
- 类变量是不会存入实例__dict__中的,只会存在于类的__dict__中
- globals/locals(可以变相操作代码)
- globals中保存了当前模块中所有的变量属性与值
- locals中保存了当前环境中的所有变量属性与值
- python变量名的解析机制(LEGB)
- 本地作用域(Local)
- 当前作用域被嵌入的本地作用域(Enclosing locals)
- 全局/模块作用域(Global)
- 内置作用域(Built-in)
- 实现从1-100每三个为一组分组
print([[x for x in range(1,101)][i:i+3] for i in range(0,100,3)])
- 什么是元类?
- 即创建类的类,创建类的时候只需要将metaclass=元类,元类需要继承type而不是object,因为type就是元类
type.__bases__ #(<class 'object'>,)
object.__bases__ #()
type(object) #<class 'type'>
class Yuan(type):
def __new__(cls,name,base,attr,*args,**kwargs):
return type(name,base,attr,*args,**kwargs)
class MyClass(metaclass=Yuan):
pass
- 什么是鸭子类型(即:多态)?
- Python在使用传入参数的过程中不会默认判断参数类型,只要参数具备执行条件就可以执行
- 深拷贝和浅拷贝
- 深拷贝拷贝内容,浅拷贝拷贝地址(增加引用计数)
- copy模块实现神拷贝
- 单元测试
- 一般测试类继承模块unittest下的TestCase
- pytest模块快捷测试(方法以test_开头/测试文件以test_开头/测试类以Test开头,并且不能带有 init 方法)
- coverage统计测试覆盖率
服务端性能优化方向
- 使用数据结构和算法
- 数据库
- 索引优化
- 慢查询消除
- slow_query_log_file开启并且查询慢查询日志
- 通过explain排查索引问题
- 调整数据修改索引
- 批量操作,从而减少io操作
- 使用NoSQL:比如Redis
- 网络io
- 批量操作
- pipeline
- 缓存
- Redis
- 异步
- Asyncio实现异步操作
- 使用Celery减少io阻塞
- 并发
- 多线程
- Gevent