Python编程实战:运用设计模式、并发和程序库创建高质量程序 阅读笔记
Python编程实战:运用设计模式、并发和程序库创建高质量程序 阅读笔记
Python编程实战:运用设计模式、并发和程序库创建高质量程序
目录
创建型设计模式
抽象工厂 @classmethod def make_xxx(Class, ...) Builder with open(filename, "w", encoding='utf-8') as f: f.write(x)多一层映射封装好吗?序列与map的unpacking:function(*args, **kwargs)super().add_title(t) #=> BaseClass.add_title(self, t) ? 工厂方法原型 for code in itertools.chain( (0x26C0,0x26C2), range(0x2654,0x2660) ): ...setattr(sys.module[__name__], name, Class) #=> globals()[name]=Class 单例 key = "{}({})".format(name, currency)结构型设计模式
适配器(Python的mock对象?):协调调用者与被调用者,使得接口一致 class Renderer(metaclass=abc.ABCMeta): @classmethoddef __subclasshook__(Class, Subclass): #内置方法isinstance()通过此方法判断arg1是否是arg2的子类 3.3+ if Class is Renderer: attributes = collections.ChainMap( *(Superclass.__dict__ for Superclass in Subclass.__mro__))methods = ("header", "paragaph", "footer")if all(method in attributes for method in methods): return True(特殊情形:and callable(method)) return NotImplemented 或 @Qtrac.has_methods("header", "paragaph", "footer")class Renderer(metaclass=abc.ABCMeta): pass 桥接:bridge接口与实现(而不是直接继承)组合 composite即容器类型的元素 修饰器 实现了__eq__和__lt__后,即可通过@functools.total_ordering支持< <= == != >= >实现decorator时,对wrapper加装饰@functools.wraps(func),可使得wrapper函数的__name__ __doc__与原func相同def wrapper(*args, **kwargs): ... return func(*args, **kwargs)类修饰器:用getattr/setattr/property等对Class对象进行操作 外观:对不同的实现抽象一套相同的接口 ?绑定方法:bound=self.f vs. unbound=Class.f 享元(Flyweight) Java:String#intern?p53 Python序列化过程中能够执行任意代码,不安全(How?) 代理:用一个对象代表另一个对象 ‘远程代理’RPyC库行为型设计模式
责任链 p61 凡是带有yield语句的函数都能作为generator,利用@coroutine及无限循环可将其变为协程(感觉这里与Scheme的CPS有点关联) @coroutinedef handler(successor):while True:
event = (yield)
successor.send(event) 命令 Undo-Redo 解释器 DSL:PLY PyParsingeval()ast.literal_eval()exec()用子进程执行代码:with subprocess.Popen([sys.executable, "-"], ...) as process: ...stderr = re.sub(", line (\d+)", lambda m: str(int(m.group(1))-offset), stderr)PyPy “沙盒” 迭代器 序列协议:实现__getitem__双参数iter(callable, sentinel):需实现__call__迭代器协议:__iter__()和__next__() 中介:实现一组接口与多个对象之间的对接(m:n连接?) 相当于GUI编程中的各种EventListener?
高级并发
计算密集型:避开GIL multiprocessing.JoinableQueue.join/task_done()multiprocessing.Queue.get/get_nowait()3.2 concurrent.futures模块 concurrent.futures.ProcessPoolExecutor I/O密集型:主要因素是网络延迟,与线程还是进程没有多大关系案例研究:并发型GUI应用 multiprocessing.Value扩充Python
PyPy JITctypes:略Cython .pxd文件: cdef extern from "hyphen.h":ctypedef struct HyphenDict: pass
HyphenDict* hnj_hyphen_load(char* filename) .pyx 与C++交互:SWIG、SIP、boost::python、CFFI
评论关闭