python 中偏函數 partial 的使用


函數的partial應用

  函數在執行時,要帶上所有必要的參數進行調用。但是,有時參數可以在函數被調用之前提前獲知。這種情況下,一個函數有一個或多個參數預先就能用上,以便函數能用更少的參數進行調用。

例如:

In [9]: from functools import partial

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

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

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

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

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

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

其實就是函數調用的時候,有多個參數 參數,但是其中的一個參數已經知道了,我們可以通過這個參數重新綁定一個新的函數,然后去調用這個新函數。

如果有默認參數的話,他們也可以自動對應上,例如:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM