Python uses functools partial function generation module partial function

The so-called partial function that is predetermined as a function of fixed parameters in the functional programming we often used, where we look at using the Python functools module partial function generation method of partial functions
python provides for a method for function function of fixed properties (not the same as a function of bias mathematical)

# 通常会返回10进制
int('12345')  # print 12345 
 
# 使用参数 返回 8进制
int('11111', 8)  # print 4681

Each had to add a parameter is too much trouble, functools provides partial methods

import functools
 
foo = functools.partial(int, base=8)
 
foo('11111')  # print 4681

It generates a fixed parameter of the new function by this method.

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 define a function int2 (), the default pass in the base = 2:

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

In this way, we convert the binary is very convenient:

>>> int2('1000000')
64
>>> int2('1010101')
85

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

So, a brief summary of the role of functools.partial is to put some parameters to a function of the fixed (that is, set the default value), returns a new function, call this new function will be easier.

Noted that the new int2 the above function, just reset the base parameter default is 2, but other values ​​can be passed in the function call:

>>> int2('1000000', base=10)
1000000

Finally, when you create a partial function, you can actually receiving function object, * args and ** kw these three parameters, when passed:

int2 = functools.partial(int, base=2)

In fact keyword arguments base fixed int () function, that is:

int2('10010')

It is equivalent to:

kw = { 'base': 2 }
int('10010', **kw)

When Incoming:

max2 = functools.partial(max, 10)

In fact, as will 10 * args part is automatically added to the left, that is:

max2(5, 6, 7)

It is equivalent to:

args = (10, 5, 6, 7)
max(*args)

Finally, I recommend a good reputation python gathering [ click to enter ], there are a lot of old-timers learning skills, learning experience, interview skills, workplace experience and other share, the more we carefully prepared the zero-based introductory information on actual project data method, every day, programmers explain the timing Python technology, to share some of the learning and the need to pay attention to small details

Published 44 original articles · won praise 56 · views 60000 +

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104909107