def add(x,y):
pass
return x + y
add(1,2)
3
def add(x):
def _add(y):
return x + y
return _add
add(1)
<function __main__.add.<locals>._add(y)>
add(1)(2)
3
import functools
def add(x,y) -> int:
return x + y
add = functools.partial(add,y=2)
add(1)
3
add = functools.partial(add,x=1)
add(y=2)#为什么要用y=2传参? add(2):错误 知识点:参数规则
3
g = lambda x:lambda y: x+y
g(1)
<function __main__.<lambda>.<locals>.<lambda>(y)>
g(1)(2)
3
def add(x):
def _add(y):
def __add(z):
return x + y + z
return __add
return _add
add(1)
<function __main__.add.<locals>._add(y)>
add(1)(2)
<function __main__.add.<locals>._add.<locals>.__add(z)>
add(1)(2)(3)
6
print('__'*32)
g = lambda x: lambda y: lambda z: x + y + z
g(1)
<function __main__.<lambda>.<locals>.<lambda>(y)>
g(1)(2)
<function __main__.<lambda>.<locals>.<lambda>.<locals>.<lambda>(z)>
g(1)(2)(3)
6
print('__'*32)
import functools
def partialadd(x:int,y:int,z:int) ->int:
return x + y + z
newpratialadd = functools.partial(partialadd,x=1)
newpratialadd
functools.partial(<function partialadd at 0x00000252435E3D08>, x=1)
newpratialadd(y=2,z=3)
6
newpratialadd = functools.partial(partialadd,1,y=2)
newpratialadd
functools.partial(<function partialadd at 0x00000252435E3D08>, 1, y=2)
newpratialadd(z=3)
6
newpratialadd = functools.partial(partialadd,1,2,z=3)#newpratialadd = functools.partial(partialadd,1,y=2,z=3)#newpratialadd = functools.partial(partialadd,1,2,3) 都可以 一个基本规则 位置参数在关键字参数前面 任意位置参数在前,keywordonly在腰,任意关键字参数在尾
newpratialadd
functools.partial(<function partialadd at 0x00000252435E3D08>, 1, 2, z=3)
newpratialadd()
6
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords. Roughly equivalent to:
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
可以看出 partial return newfunc 而newfunc返回func
偏函数返回了一个新的函数,而新的函数最终调用原函数
偏函数与柯里化区别:
(1)柯里化是将一个多参的函数转换成多个单参的函数,也就是将一个 n 元函数转换成 n 个一元函数
(2)局部应用则是固定一个函数的一个或者多个参数,也就是将一个 n 元函数转换成一个 n - x 元函数
n个一元 一个n-x元
1.动态生成函数
2.减少参数
3.延迟计算
border="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=540161486&auto=1&height=66">