Python重点知识汇总,建议收藏

本文汇总了Python编程中的重要知识点,包括Python2与3的差异,如print变为函数,除法返回浮点数,长整型消失等。讲解了Python3新增的特性和库,如asyncio、enum等,并探讨了高级解包、元类、协程等概念。此外,还介绍了进程间通信、单元测试、垃圾回收机制等进阶话题,并提供了各种数据结构和算法的实例。文章还涉及数据库优化、Redis使用、网络I/O模型以及服务端性能优化策略等。
摘要由CSDN通过智能技术生成

   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:'&lt;h1&gt;I&#x27;m Jim&lt;/h1&gt;'
    html.unescape('&lt;h1&gt;I&#x27;m Jim&lt;/h1&gt;') # <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(ta
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值