翻译自:https://pymotw.com/3/functools/index.html
functools模块提供了调整和扩展函数以及其他 callable objects的工具方法。
装饰器(Decorators)
1)partial函数
partial函数可用来修改函数的默认参数值,增加额外的位置参数(positional arguments)或名称参数( named arguments),你不需再重新定义函数,只需像使用原函数一样的使用partial包裹后的函数。
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()
#结果
myfunc:
object: <function myfunc at 0x1007a6a60>
__name__: myfunc
called myfunc with: ('a', 3)
partial with named default:
object: functools.partial(<function myfunc at 0x1007a6a60>,
b=4)
func: <function myfunc at 0x1007a6a60>
args: ()
keywords: {
'b': 4}
called myfunc with: ('passing a', 4)
called myfunc with: ('override b', 5)
partial with defaults:
object: functools.partial(<function myfunc at 0x1007a6a60>,
'default a', b=99)
func: <function myfunc at 0x1007a6a60>
args: ('default a',)
keywords: {
'b': 99}
called myfunc with: ('default a', 99)
called myfunc with: ('default a', 'override b')
Insufficient arguments:
Traceback (most recent call last):
File "functools_partial.py", line 51, in <module>
p1()
TypeError: myfunc() missing 1 required positional argument: 'a'
partial不仅可用于函数,其他的 callable object也可以也可以使用。
import functools
class MyClass:
"Demonstration class for functools"
def __call__(self, e, f=6):
"Docstring for MyClass.__call__"
print(' called object with:', (self, e, f))
def show_details(name, f):
"Show details of a callable object."
print('{}:'.format(name))
print(