Expert Python Programing
cheatsheet
Chapter1
待补充
Chapter2
列表推导 []
enumerate
{推导} -> set集合
collections类
deque 类似列表(list)的容器,实现了在两端快速添加(append)和弹出(pop)
namedtuple 创建命名元组子类的工厂函数
OrderedDict 字典的子类,保存了他们被添加的顺序
defaultdict
defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,可以实例化一个值作为默认值
defaultdict(list)
该类除了接受类型名称作为初始化函数的参数之外,还可以使用任何不带参数的可调用函数,例如:
defaultdict(lambda: 0)
迭代器
__next__
__iter__
yield
def fibonacci(): a, b = 0, 1 while True: yield b a, b = b, a + b
send
import time def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s...' % n) time.sleep(.1) r = '200 OK' def produce(c): next(c) n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close() if __name__=='__main__': c = consumer() produce(c)
装饰器
实现了自己__call__方法的类的实例
语法糖
使用functools模块内置wraps()装饰器打造的装饰器可以保存函数元数据如函数文档字符串
用于 参数检查 缓存 代理 上下文提供者(锁)
from time import time def timer(function): def wrapper(*args, **kwargs): before = time() result = function(*args, **kwargs) after = time() print('Run time is %s' % (after - before)) return result return wrapper @timer def add_dec(x, y=10): return x + y @timer def sub_dec(x, y=10): return x - y
with语句
Context Manager
from sqlite3 import connect from contextlib import contextmanager @contextmanager def temptable(cur): cur.execute('create table points(x int, y int)') print('created table') try: yield finally: cur.execute('drop table points') print('dropped table') with connect('test.db') as conn: cur = conn.cursor() with temptable(cur): cur.execute('insert into points (x, y) values(1, 1)') cur.execute('insert into points (x, y) values(1, 2)') cur.execute('insert into points (x, y) values(2, 1)') cur.execute('insert into points (x, y) values(2, 2)') for row in cur.execute("select x, y from points"): print(row)
del is the fastest method for removing a key from a Python dictionary
Chapter4
在Python中,使用二进制按位运算来合并选项是很常见的。使用OR(
|
)运算符可以将多个选项合并到一个整数中,而使用AND(&
)运算符则可以检查该选项是否在整数中
Chapter13
并发
多线程multithreading
多进程multiprocessing
异步编程
协程Coroutines
Tasklets
Green trheads
异步编程
async和await
Last updated
Was this helpful?