functools模块的作用
functools模块提供了一些工具来调整或扩展函数和其他callable对象,从而不必完全重写。
1、functools.partial,给函数默认传参,再使用函数一样的调用方式的示例
import functools def myfunc(a, b=2): ''' 定义myfunc函数,打印变量值 ''' print(' called myfunc with:', (a, b)) def show_details(name, f, is_partial=False): "传入函数名和函数的对象,判断是否使用functools工具,进行参数的打印调用" 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) # 运行结果 # myfunc: # object: <function myfunc at 0x000001E15CD045E8> # __name__: myfunc # called myfunc with: ('a', 3) print() p1 = functools.partial(myfunc, b=4) show_details('partial with named default', p1, True) # 运行结果 # partial with named default: # object: functools.partial(<function myfunc at 0x000002720F1D4678>, b=4) # func: <function myfunc at 0x000002720F1D4678> # args: () # keywords: {'b': 4} # 直接使用functools修饰一个函数,让调用变得更加简单 p1('passing a') p1('override b', b=5) print() p2 = functools.partial(myfunc, 'default a', b=99) show_details('partial with defaults', p2, True) # 运行结果 # partial with defaults: # object: functools.partial(<function myfunc at 0x000002838A8445E8>, 'default a', b=99) # func: <function myfunc at 0x000002838A8445E8> # args: ('default a',) # keywords: {'b': 99} p2() # called myfunc with: ('default a', 99) p2(b='override b') # called myfunc with: ('default a', 'override b') print() print('参数缺少') p1() # TypeError: myfunc() missing 1 required positional argument: 'a'