Example Analysis of partial function partial usage in python, pythonpartial
This example describes the usage of partial function partial in python. Share it with you for your reference. The details are as follows:
When a function is executed, all necessary parameters must be included for calling. However, sometimes the parameters can be known in advance before the function is called. In this case, one or more parameters of a function can be used in advance, so that the function can be called with fewer parameters.
For example:
In [9]: from functools import partialIn [10]: def add(a,b):....: return a+b....:In [11]: add(4,3)Out[11]: 7In [12]: plus = partial(add,100)In [13]: plus(9)Out[13]: 109In [14]: plus2 = partial(add,99)In [15]: plus2(9)Out[15]: 108
Actually, when a function is called, there are multiple parameter parameters, but one of them is known. We can use this parameter to re-bind a new function, then call the new function.
If there are default parameters, they can also be automatically matched, for example:
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 definedIn [19]: plus3 = partial(add,101)In [20]: plus3(1)Out[20]: 102In [21]: plus3 = partial(add2,101)In [22]: plus3 = partial(add2,101) (1)Out[22]: 104In [23]: plus3(1)Out[23]: 104In [24]: plus3(1,2)Out[24]: 104In [25]: plus3(1,3)Out[25]: 105In [26]: plus3(1,30)Out[26]: 132
I hope this article will help you with Python programming.