python 中偏函数 partial 的使用

函数的partial应用python

  函数在执行时,要带上全部必要的参数进行调用。可是,有时参数能够在函数被调用以前提早获知。这种状况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调用。函数

例如:ip

In [9]: from functools import partialinput

In [10]: def add(a,b):
....: return a+b
....: ast

In [11]: add(4,3)
Out[11]: 7import

In [12]: plus = partial(add,100)module

In [13]: plus(9)
Out[13]: 109im

In [14]: plus2 = partial(add,99)call

In [15]: plus2(9)
Out[15]: 108tools

其实就是函数调用的时候,有多个参数 参数,可是其中的一个参数已经知道了,咱们能够经过这个参数从新绑定一个新的函数,而后去调用这个新函数。

若是有默认参数的话,他们也能够自动对应上,例如:

In [17]: def add2(a,b,c=2):
....: return a+b+c
....:

In [18]: plus3 = partail(add,101)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/Users/yupeng/Documents/PhantomJS/<ipython-input-18-d4b7c6a6855d> in <module>()
----> 1 plus3 = partail(add,101)

NameError: name 'partail' is not defined

In [19]: plus3 = partial(add,101)

In [20]: plus3(1)
Out[20]: 102

In [21]: plus3 = partial(add2,101)

In [22]: plus3 = partial(add2,101) (1)
Out[22]: 104

In [23]: plus3(1)
Out[23]: 104

In [24]: plus3(1,2)
Out[24]: 104

In [25]: plus3(1,3)
Out[25]: 105

In [26]: plus3(1,30)Out[26]: 132

相关文章
相关标签/搜索