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

相關文章
相關標籤/搜索