Python practical notes (16) functional programming - partial function

Suppose we want to convert a large number of binary strings, it is very troublesome to pass in each time int(x, base=2), so we thought that we can define a int2()function and pass it in by default base=2:

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

In this way, it is very convenient for us to convert binary:

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

functools.partialIt is to help us create a partial function, we don't need to define it ourselves int2(), we 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 

Therefore, the function of a simple summary functools.partialis to fix some parameters of a function (that is, set default values), return a new function, and call this new function will be simpler.

When creating a partial function, you can actually receive the function object *argsand **kwthese three parameters (in fact, I didn't understand the second half of the original text)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325844816&siteId=291194637