When a function has many parameters, the caller needs to provide multiple arguments. If you reduce the number of parameters, you can simplify the burden on the caller.
For example, the Int () function converts a string to an integer, and when only the string is passed in, the Int () function defaults to decimal conversion:
>>> int ('12345')12345
However, the Int () function also provides an additional base parameter with a default value of 10 for decimal. If you pass in the base parameter, you can do an N-ary conversion:
>>> Int ('12345', base=8)5349>>> int ('12345 ', 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:
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.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:
Import functools>>> int2 = functools.partial (int, base=2)>>> int2 (' 1000000')64>>> int2 ('1010101')85
So, functools.partial can turn a function with many parameters into a new function with fewer parameters, and fewer parameters need to specify a default value at the time of creation, so the difficulty of the new function call is reduced.
Python partial function