Usage of python Partial Function partial
- 2021-12-11 08:33:10
- OfStack
1. What is the partial function partial
python provides a function with fixed properties for functions
2. The role of partial function
Fix some parameters of a function (that is, set the default value) and return a new function
3. The Grammar of Partial Functions
To use partial functions, you must first import
from functools import partial
Function format:
partial(func, *args, **kwargs)
func
Represents the function name
*args
:
func
Indefinite length parameters of functions
**kwargs
:
func
Keyword parameters of the function
4. Cases
Case 1
from functools import partial
bin2dec = partial(int, base=2) # Put int Set the conversion of to 2 It's binary, here base Yes int The function represents the parameters of the binary system.
print(bin2dec('0b10001') ) # 17
print(bin2dec('10001')) # 17
hex2dec = partial(int, base=16) # Put int Set the conversion of to 16 Binary system
print(hex2dec('0x67')) # 103
print(hex2dec('67')) # 103
Case 2
partial_max = partial(max, 100)
print(partial_max(1, 2, 99)) # 100
Above is for
max()
Function sets 1 default argument
100
Returns 1 new function when we pass in the parameter
(1, 2, 99)
There is actually one default value in the parameter
100
, equivalent to
(100, 1, 2, 99)
So the maximum value obtained is
100
These applications of partial functions seem simple, but they are very useful and can be implemented well
DRY
Principle, save programming costs.