Chapter 3 python3, python3
Note that the partial function here is different from the partial function in the mathematical sense. Partial function is introduced after version 2.5 and is part of functional programming. As we mentioned in the previous chapter, you can reduce the difficulty of function calling by setting the default value of the parameter. This can also be done by partial functions. Example:
The int () function can convert a string to an integer. when only a string is input, the int () function is converted in decimal by default:
Print ("\ '000000' to int:", int ('20140901 '))
The above code outputs:
'20180101' to int: 12345
However, the int () function also provides additional base parameters. The default value is 10. If you input the base parameter, you can perform the N-hexadecimal conversion:
Print ("8-in-order \ '1970 \ 'to 10-in-order int:", int ('20140901', base = 8 ))
The above code outputs:
Convert the 8-digit '200' to a 10-digit int: 12345
Suppose we want to convert a large number of binary strings, and it is very troublesome to input int (x, base = 2) every time. So we thought we could define a int2 () function, by default, base = 2 is passed in:
def int2(x, base=2): return int(x, base)print(int2('10000'))print(int2('10001'))
The above code outputs:
1617
In python, functools. partial is used to create a partial function. You do not need to define int2 () by yourself. You can directly use the following code to create a new function int2:
import functoolsint2 = functools.partial(int, base=2)print(int2('10000'))print(int2('10001'))
The above code outputs:
1617
Therefore, functools. partial is used to fix some parameters of a function (that is, to set the default value) and return a new function, which is easier to call.
Note that the new int2 function above only resets the default value of 2 for the base parameter, but you can also input other values when calling the function:
import functoolsint2 = functools.partial(int, base=2)print(int2('10000', base=10))print(int2('10001'))
The above code outputs:
1000017
When you use functools. partial to create partial functions, functools. partial receives function objects, * args, and ** kw parameters in sequence. For example:
int2 = functools.partial(int, base=2)
Actually, the keyword parameter of the int () function is fixed.base, That is:
int2('10010')
Equivalent:
kw = { 'base': 2 }int('10010', **kw)
When passed in:
max2 = functools.partial(max, 10)
In fact10As*argsIs automatically added to the left, that is:
max2(5, 6, 7)
Equivalent:
args = (10, 5, 6, 7)max(*args)
The applications of partial functions seem simple, but they are very useful and can execute the DRY principle well.
Note:
- Principle 1: Don't Repeat Yourself
- Principle 2: Keep Simple direct (Keep it Simple Stupid)
- Principle 3: You don't Need It (You Ain't Gonna Need It)
Of course, I personally think we do not need to blindly pursue the three principles!