In simple terms, partial functionsfunctools.partial
The getFunction () function returns a new function by fixing some of its parameters (that is, setting the default values), making it easier to call the new function.
For example, to convert a string to an integer, we can call int() :
>>> int('110101', base=2)
53
Copy the code
If we need a large number of these conversions in a single project, it would be too much trouble to write the code each time, so we can define a new function to call ourselves:
>>> def new_int(x, base=2):
return int(x, base)
Copy the code
In the above code, we fixed the int() argument to base=2 and defined a new function new_int(). Now let’s look at the result of calling the new function:
>>> new_int('1000000')
64
>>> new_int('1010101')
85
Copy the code
Functools.partial does just that in Python. Instead of defining new_int(), we can create a new function new_int() as in the following example:
>>> import functools
>>> new_int = functools.partial(int, base=2)
>>> new_int('101010')
42
>>> new_int('10001000')
136
Copy the code
So the function functools.partial is to fix some of the parameters of a function (that is, set the default values) and return a new function, making it easier to call the new function. In the example above, we set the base of new_int() to default to 2, But we can still pass in other values when new_int() is called:
>>> new_int('123456', base=8)
42798
Copy the code
Finally, when you create a partial function, you can actually take the function object, *args, and **kw.
>>> new_int = functools.partial(int, base=2)
Copy the code
Int (); new_int(‘10001000’); int(‘ base ‘);
>>> kw = { 'base': 2 }
>>> int('10001000', **kw)
Copy the code
When we define a partial function:
>>> new_max = functools.partial(max, 3)
Copy the code
New_max (6, 24, 18, -10) is called, equivalent to:
>>> args = (3, 6, 24, 18, -10)
>>> max(*args)
24
Copy the code
ps:
The default base of the int() function is 10, which converts a string to a decimal integer. When using the default base value, you can pass in only the string and omit the base value, for example, int(‘123’). Similarly, int(‘10001000’, base=2) means to convert 10001000 from binary to decimal. This function can also be written as int(‘10001000’, 2).