Suppose we want to convert a large number of binary strings, it is very troublesome to pass in each time int(x, base=2)
, so we thought that we can define a int2()
function and pass it in by default base=2
:
def int2(x, base=2): return int(x, base)
In this way, it is very convenient for us to convert binary:
>>> int2('1000000')
64
>>> int2('1010101') 85
functools.partial
It is to help us create a partial function, we don't need to define it ourselves int2()
, we 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
Therefore, the function of a simple summary functools.partial
is to fix some parameters of a function (that is, set default values), return a new function, and call this new function will be simpler.
When creating a partial function, you can actually receive the function object *args
and **kw
these three parameters (in fact, I didn't understand the second half of the original text)