首先我们看看官方文档的定义:
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
我们一步一步的读:
简单的示例说明:
from functools import partial
def add(x, y, z):
return x + y + z
a1 = partial(add, 10, 20)
# 60
print(a1(30))
# functools.partial(, 10, 20)
print(a1)
分部解释:
复杂的示例说明:
如果我的partial函数第二值传的是个函数,会发生什么事情呢?看如下示例。
def sub(x, y):
return x - y
def div(x, y):
return x/y
def attach_wrap(func1, func2=None):
if func2 is None:
return partial(attach_wrap, func1)
setattr(func1, func2.__name__, func2)
return func1
sub1 = attach_wrap(sub)
print(sub1)
sub2 = sub1(div)
print(sub2)
print(sub2(20, 10)) //10
print(sub2.div(20, 10)) //2.0
解释说明:
上面的这种写法经常可以用来在一个函数上绑定另一个函数:
def sub(x, y):
return x - y
def attach_wrap(func1, func2=None):
if func2 is None:
return partial(attach_wrap, func1)
setattr(func1, func2.__name__, func2)
return func1
@attach_wrap(sub)
def div(x, y):
return x/y
print(sub(10, 5))
print(sub.div(10, 5))