偏函数(functools.partial)
可代为传递参数
示例1
def func(a1,a2,a3): return a1 * a2 * a3 import functools f1 = functools.partial(func,111) f2 = functools.partial(func,222) v1 = f1(2,3) v2 = f2(2,3) print(v1,v2) # 116 227
示例2
import functools class RequestContext(object): def __init__(self): self.request = 'aaaaa' self.session = 'bbbbb' obj = RequestContext() def get_data(name): return getattr(obj,name) request_proxy = functools.partial(get_data,'request') session_proxy = functools.partial(get_data,'session') request = request_proxy() session = session_proxy() print(request,session) # aaaaa bbbbb