What we are explaining today is the partial function, which is a concept introduced from Python2.5, which is called by the user via the Functools module.
The partial function takes the function that is to be hosted as partial() the first parameter of the function, and each parameter of the original function is followed by the arguments of the function partial() , unless the keyword argument is used.
The language description may not understand how the partial function is used, so give a common example to illustrate. In this example, we implement a residual function, for the integer 100, to obtain the remainder of the 100%m for different number m.
Span style= "line-height:0px;" > < span>
>>> from Functools import partial>>> >>> def mod (n, m):>>> return n m>>> >>> mod_by_100 = partial (mod, +) >>> >>> print mod (7) 2>>> Print mod_by_100 ( 7) 2
Since previously seen examples of general selection of addition or multiplication to explain, can not understand the position of the partial function parameters, easy to give the second parameter of the partial is also the original function of the second parameter of the illusion, so I choose the mod here to explain.
And for the case with the keyword parameter, it can not follow the original function of the parameter location and number. Let's look at an example of how to make a different binary conversion.
>>> from functools import partial>>> >>> bin2dec = partial (int, base=2) >>> Print bin 2dec (' 0b10001 ') 17>>> print bin2dec (' 10001 ') 17>>> >>> hex2dec = partial (int, base=16) > >> print Hex2dec (' 0x67 ') 103>>> print Hex2dec (' 67 ') 103
Python functional Programming--partial function