Home > Backend Development > Python Tutorial > python中偏函数partial用法实例分析

python中偏函数partial用法实例分析

WBOY
Release: 2016-06-10 15:09:46
Original
1904 people have browsed it

本文实例讲述了python中偏函数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

Copy after login

其实就是函数调用的时候,有多个参数 参数,但是其中的一个参数已经知道了,我们可以通过这个参数重新绑定一个新的函数,然后去调用这个新函数。

如果有默认参数的话,他们也可以自动对应上,例如:

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

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template