Excerpt: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 00143184474383175eeea92a8b0439fab7b392a8a32f8fa000
This article is completely used for personal review, invasion and deletion;
functools.partial is to help us create a biased function, without our own definition int2() , you can create a new function directly using the following code int2 :
Import Functools functools.partial (int, base=2)>>> int2 ('1000000')64>>> int2 (' 1010101')85
So, the simple functools.partial Summary of the function is to put some parameters of a function fixed (that is, set the default), return a new function, call this new function is more simple.
Notice that the new function above int2 simply base sets the parameter back to the default value 2 , but can also pass in other values when the function is called:
>>> int2 ('1000000', base=10)1000000
Finally, when you create a partial function, you can actually receive the function object, *args and **kw These 3 parameters, when passed in:
Int2 = functools.partial (int, base=2)
The key parameter of the int () function is actually fixed base , i.e.:
Int2 ('10010')
Equivalent:
' Base ': 2 }int ('10010', **kw)
When incoming:
Max2 = Functools.partial (max, 10)
Will actually 10 *args add the part automatically to the left, namely:
MAX2 (5, 6, 7)
Equivalent:
args = (5, 6, 7) max (*args)
The result is 10 .
Summary
When a function has too many arguments and needs to be simplified, it functools.partial can be used to create a new function that can fix some of the parameters of the original function , making it easier to invoke.
Python Learning notes (11) Partial function