python中partial的使用規(guī)則

前天看到了partial的一個(gè)新用法,記錄一下。

概念

函數(shù)聲明如下:

functools.partial(func[,*args][, **keywords])

返回一個(gè)可以像函數(shù)一樣被調(diào)用的partial實(shí)例,在調(diào)用時(shí)使用args和keywords參數(shù)。使用python實(shí)現(xiàn)時(shí),類(lèi)似于:

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

通常的使用方法

通常的用法是在原函數(shù)聲明的參數(shù)中,從前往后連續(xù)將參數(shù)值固定:

>>> from functools import partial
>>> def test_partial(a, b, c, d):
...     print a,b,c,d
...
>>> test1 = partial(test_partial,1,2)
>>> test1(3,4)
1 2 3 4
>>> test2 = partial(test_partial,1,2,3,4)
>>> test2(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test_partial() takes exactly 4 arguments (5 given)

這通常只能把前面的參數(shù)固定,假如有個(gè)需求和現(xiàn)有的不一樣,需要使后面的參數(shù)固定,該怎么做?可以使用下面的方法

新的使用方法

1.使用關(guān)鍵字參數(shù)

>>> test3 = partial(test_partial, d=4)
>>> test3(1,2,3)
1 2 3 4
  1. 其限制
>>> test4 = partial(test_partial, c=3, d=4)
>>> test4(1,2)
1 2 3 4
>>> test5 = partial(test_partial, b=2, d=4)
>>> test5(1,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test_partial() got multiple values for keyword argument 'b'

可以看到,當(dāng)只對(duì)b和d賦值,然后調(diào)用時(shí)會(huì)報(bào)錯(cuò),關(guān)鍵值參數(shù)有多個(gè)值。我們?cè)囋囋谡{(diào)用時(shí),使用關(guān)鍵字c看看:

>>> test5(1,c=3)
1 2 3 4

可以看出,這樣也可以正常調(diào)用。

  1. 如果對(duì)前面的參數(shù)默認(rèn)賦值,會(huì)出現(xiàn)什么情況?是不是和以前一樣,只需要使用列表參數(shù)就行了?
>>> test6 = partial(test_partial, a=1,b=3)
>>> test6(3,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test_partial() got multiple values for keyword argument 'a'

顯然不行,最后還是得使用關(guān)鍵字參數(shù)進(jìn)行調(diào)用。

總結(jié)

從上面的運(yùn)行結(jié)果來(lái)看,使用partial規(guī)則如下:

  1. 將前面連續(xù)的參數(shù)固定,就可以直接繼續(xù)按照原來(lái)的參數(shù)繼續(xù)調(diào)用。如
 >>> test1 = partial(test_partial,1,2)
 >>> test1(3,4)
 1 2 3 4
  1. 將后面的連續(xù)參數(shù)固定,就可以直接繼續(xù)使用原來(lái)的參數(shù)進(jìn)行調(diào)用。如
>>> test4 = partial(test_partial, c=3, d=4)
>>> test4(1,2)
1 2 3 4
  1. 如果默認(rèn)參數(shù)值不是連續(xù)的或者是直接對(duì)前面的連續(xù)參數(shù)賦值,那么就需要使用關(guān)鍵字參數(shù)進(jìn)行調(diào)用,如
>>> test5(1,c=3)
1 2 3 4
>>> test6(c=3,d=4)
1 3 3 4
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容