The Python functools
module provides many useful features, one of which is the partial function (Partial function). Note that partial function here on the partial function and mathematical meaning is not the same.
Introducing the function parameters, we talked about, by setting default values for the parameters, you can reduce the difficulty of function calls. The partial function can also do this. For example as follows:
int()
Function can be converted to an integer string, only when an incoming string, int()
default function decimal conversion:
>>> int('12345')
12345
But the int()
function also provides additional base
parameters, the default value 10
. If the incoming base
parameters, you can do the N-ary conversion:
>>> int('12345', base=8)
5349
>>> int('12345', 16) 74565
Suppose you want to convert a large number of binary string, each time passing int(x, base=2)
very troublesome, so, we think, can define a int2()
function, the default base=2
pass in:
def int2(x, base=2): return int(x, base)
In this way, we convert the binary is very convenient:
>>> int2('1000000')
64
>>> int2('1010101') 85
functools.partial
Is to help us create a partial function, do not need our own definition int2()
, you can directly use the following code to create a new function int2
:
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000') 64 >>> int2('1010101') 85
So, a brief summary functools.partial
of the role is to put some parameters to a function of the fixed (that is, set the default value), returns a new function, call this new function will be easier.
It noted that the new above int2
function, is the only base
parameter to reset the default value 2
, but other values can be passed in the function call:
>>> int2('1000000', base=10)
1000000
Finally, when you create a partial function, can actually receiving function objects, *args
and **kw
these three parameters, when passed:
int2 = functools.partial(int, base=2)
In fact keyword parameters fixed int () function base
, that is:
int2('10010')
It is equivalent to:
kw = { 'base': 2 }
int('10010', **kw)
When Incoming:
max2 = functools.partial(max, 10)
In fact, it will 10
as *args
part automatically added to the left, that is:
max2(5, 6, 7)
It is equivalent to:
args = (10, 5, 6, 7)
max(*args)
Results 10
.
summary
When too much the number of function parameters, if necessary simplicity, functools.partial
you can create a new function, this new function may be a fixed part of the original function parameters lived so much simpler when you call.
Original URL: https: //www.liaoxuefeng.com/wiki/1016959663602400/1017454145929440