Python'sfunctoolsThe module provides a number of useful functions, one of which is the partial function. It is important to note that the partial function here is not the same as the partial function in mathematical sense.
When we introduce the function parameters, we can reduce the difficulty of the function call by setting the default value of the parameter. The partial function can do this, too. Examples are as follows:
int()Functions can convert a string to an integer, and when passed in only the string, the int() function defaults to decimal conversion:
int(‘12345‘)12345
But int() the function also provides additional base parameters, the default value is 10 . If you pass in base a parameter, you can do an n-binary conversion:>>> int(‘12345‘, base=8
5349>>> int(‘12345‘, 16)74565
Assuming that you want to convert a large number of binary strings, each time it is very troublesome to pass in, int(x, base=2) so, we think, can define a int2() function, the default is base=2 passed in:
def int2(x, base=2): return int(x, base)
In this way, it is very convenient for us to convert the binary:
>>> int2(‘1000000‘)64>>> int2(‘1010101‘)85
functools.partialis to help us create a biased function, without our own definition int2() , you can create a new function directly using the following code int2 :
>>> import functools>>> int2 = functools.partial(int, base=2)>>> int2(‘1000000‘)64>>> int2(‘1010101‘)85
So, the simple summary functools.partial of the function is to put some parameters of a function fixed (that is, set the default), return a new function, call this new function is more simple.
Notice that the new function above int2 simply base sets the parameter back to the default value 2 , but can also pass in other values when the function is called:
>>> int2(‘1000000‘, base=10)1000000
Finally, when you create a partial function, you can actually receive the function object, *args and **kw These 3 parameters, when passed in:
int2 = functools.partial(int, base=2)
The key parameter of the int () function is actually fixed base , i.e.:
int2(‘10010‘)
Equivalent:
‘base‘: 2 }int(‘10010‘, **kw)
When incoming:
max2 = functools.partial(max, 10)
Will actually 10 *args add the part automatically to the left, namely:
max2(5, 6, 7)
Equivalent:
args = (10, 5, 6, 7)max(*args)
The result is 10 .
Summary
When a function has too many arguments and needs to be simplified, it functools.partial can be used to create a new function that can fix some of the parameters of the original function, making it easier to invoke.
Python functional Programming-bias function