Describes partial functions in Python in detail.
The Python functools module provides many useful functions, one of which is the Partial function ). Note that the partial function here is different from the partial function in the mathematical sense.
When introducing function parameters, we will talk about how to reduce the difficulty of function calling by setting the default values of parameters. This can also be done by partial functions. Example:
The int () function can convert a string to an integer. when only a string is input, the int () function is converted in decimal by default:
>>> int('12345')12345
However, the int () function also provides additional base parameters. The default value is 10. If you input the base parameter, you can perform the N-hexadecimal conversion:
>>> int('12345', base=8)5349>>> int('12345', 16)74565
Suppose we want to convert a large number of binary strings, and it is very troublesome to input int (x, base = 2) every time. So we thought we could define a int2 () function, by default, base = 2 is passed in:
def int2(x, base=2): return int(x, base)
In this way, binary conversion is very convenient:
>>> int2('1000000')64>>> int2('1010101')85
Functools. partial is used to create a partial function. You do not need to define int2 () by yourself. You can use the following code to create a new function int2:
>>> import functools>>> int2 = functools.partial(int, base=2)>>> int2('1000000')64>>> int2('1010101')85
Therefore, functools is briefly summarized. the role of partial is to fix some parameters of a function (that is, to set the default value) and return a new function. It is easier to call this new function.
Note that the new int2 function above only resets the default value of 2 for the base parameter, but you can also input other values when calling the function:
>>> int2('1000000', base=10)1000000
Finally, when you create a partial function, you can actually receive the function objects, * args, and ** kw parameters:
int2 = functools.partial(int, base=2)
In fact, the keyword parameter base of the int () function is fixed, that is:
int2('10010')
Equivalent:
kw = { base: 2 }int('10010', **kw)
When passed in:
max2 = functools.partial(max, 10)
In fact, 10 will be automatically added to the left as a part of * args, that is:
max2(5, 6, 7)
Equivalent:
args = (10, 5, 6, 7)max(*args)
The result is 10.
Summary
When the number of parameters of a function is too large and needs to be simplified, you can use functools. partial to create a new function. This new function can fix some parameters of the original function, making it easier to call.