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, theint () 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 ten. If you pass in the base parameter, you can do an N -ary conversion:
>>> int (' 12345 ', base=8) 5349>>> int (' 12345 ', 16) 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.
Task
In the 7th section, we can implement ignoring case ordering by passing in the custom sort function in the higher-order function of sorted . Please use functools.partial to turn this complex call into a simple function:
Sorted_ignore_case (iterable)
-
- ? What's going on?
-
-
To fix The CMP parameter for sorted () , you need to pass in a sort function as the default value for the CMP .
Reference code:
Import functoolssorted_ignore_case = functools.partial (sorted, Cmp=lambda S1, s2:cmp (S1.upper (), S2.upper ())) print Sorted_ignore_case ([' Bob ', ' about ', ' Zoo ', ' credits '])
Python partial function