functools模块提供了一些工具来调整或扩展函数和其他callable对象,从而不必完全重写。
functools模块提供的主要工具就是partial类,可以用来“包装”一个有默认参数的callable对象。得到的对象本身就是callable,可以把它看作是原来的函数。它与原函数的参数完全相同,调用时还可以提供额外的位置或命名函数。可以使用partial而不是lambda为函数提供默认参数,有些参数可以不指定。
1.1.1 部分对象第一个例子显示了函数myfunc()的两个简单partial对象。show_details()的输出中包含这个部分对象(partial object)的func、args和keywords属性。
import functools def myfunc(a, b=2): "Docstring for myfunc()." print(' called myfunc with:', (a, b)) def show_details(name, f, is_partial=False): "Show details of a callable object." print('{}:'.format(name)) print(' object:', f) if not is_partial: print(' __name__:', f.__name__) if is_partial: print(' func:', f.func) print(' args:', f.args) print(' keywords:', f.keywords) return show_details('myfunc', myfunc) myfunc('a', 3) print() # Set a different default value for 'b', but require # the caller to provide 'a'. p1 = functools.partial(myfunc, b=4) show_details('partial with named default', p1, True) p1('passing a') p1('override b', b=5) print() # Set default values for both 'a' and 'b'. p2 = functools.partial(myfunc, 'default a', b=99) show_details('partial with defaults', p2, True) p2() p2(b='override b') print() print('Insufficient arguments:') p1()