The partial function python

Partial function:

When a function has many parameters, the caller will need more than one parameter. If you reduce the number of parameters, you can simplify the burden on the caller. For example, int () function can convert the string to an integer only when an incoming string, int () function default decimal conversion, but int () function also provides additional base parameters, the default value is 10. If the incoming base parameters, you can do the N-ary conversion:

>>> int('12345', base=8)
5349
>>> int('12345', 16)
74565

Suppose you want to convert a large number of binary string, each incoming int (x, base = 2) is very difficult, so we thought, you can customize a function int2 (), the default pass in the base = 2:

def int2(x, base=2):
    return int(x, base)

But is there an easier way? functools.partial is to help us create a partial function, do not need our own definition 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

functools.partial can be a function of many parameters become less of a new parameter function, fewer parameters need to specify a default value when you create, so the difficulty of the new function calls is reduced.

 

Guess you like

Origin www.cnblogs.com/CYHISTW/p/10960157.html