Python's Functools module provides a number of useful features, 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:
the int () function converts a string to an integer, and the Int () function defaults to decimal conversions when only the string is passed in:
?
1
2
>>> int (' 12345 ')
12345
However, the Int () function also provides an additional base parameter with a default value of 10. If you pass in the base parameter, you can do an n-ary conversion:
?
1
2
3
4
>>> int (' 12345 ', base=8)
5349
>>> int (' 12345 ', 16)
74565
Assuming that you want to convert a large number of binary strings, it is very troublesome to pass in int (x, base=2) every time, so we think that we can define a function of Int2 () and pass the base=2 in by default:
?
1
2
def int2 (x, base=2):
return int (x, Base)
In this way, it is very convenient for us to convert the binary:
?
1
2
3
4
>>> int2 (' 1000000 ')
64
>>> int2 (' 1010101 ')
85
Functools.partial is to help us create a biased function, we do not need to define INT2 (), you can directly use the following code to create a new function Int2:
?
1
2
3
4
5
6
>>> Import Functools
>>> Int2 = functools.partial (int, base=2)
>>> int2 (' 1000000 ')
64
>>> int2 (' 1010101 ')
85
So, a simple summary of Functools.partial's function is to fix some parameters of a function (that is, to set the default value), return a new function, call this new function is simpler.
Notice that the new Int2 function above simply re-sets the base parameter to the default value of 2, but can also pass in other values when the function is called:
?
1
2
>>> int2 (' 1000000 ', base=10)
1000000
Finally, when you create a partial function, you can actually receive the 3 parameters of the function object, *args, and **kw, when passed in:
?
1
Int2 = functools.partial (int, base=2)
The keyword parameter base of the int () function is actually fixed, i.e.:
?
1
Int2 (' 10010 ')
Equivalent:
?
1
2
KW = {Base:2}
Int (' 10010 ', **kw)
When incoming:
?
1
Max2 = Functools.partial (max, 10)
Will actually automatically add 10 as part of the *args to the left, namely:
?
1
MAX2 (5, 6, 7)
Equivalent:
?
1
2
args = (10, 5, 6, 7)
Max (*args)
The result is 10.
About the partial function reprint in Python