A Summary of the Usage of python Partial Function

  • 2021-11-13 08:31:50
  • OfStack

Description

1. When the function has too many parameters and needs to be simplified, a new function can be created by using functools. partial.
2. This new function can fix some parameters of the original function, which makes it easier to call.

The effect is to fix some parameters of a function (that is, set default values) and return a new function, which will be easier to call.

Instances


>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85

Extension of basic knowledge points:

1. Why use partial functions

If we define a function, say, add four numbers to add (one, two, three, four), there are many functions in the upper layer that need to call this function. In these calls, 80% of the calls pass parameters one=1 and two=20. If we enter the same parameters every time, it is boring and wasteful. Of course, we can solve this problem by default parameters; But what if we also need parameters one=2, two=10? So, we need a function that can transform a function with any number of parameters into a function object with remaining parameters.

2. What is a partial function

From the above, we probably understand what a partial function is: Simply put, a partial function is an implementation of a certain function with fixed parameters, so we need:

1) Name the partial function

2) Passing fixed parameters


from operator import add,mul
from functools import partial
add1=partial(add,1)
add(2,4) #6
add(1,2) #3

Related articles: