preface

Functools. partial is a function wrapped in functools.partial. Functools. partial is a function wrapped in functools.partial is a function wrapped in functools.partial.Copy the code

Functools. partial basic use

Functools. partial is used for higher-order functions, mainly to build a new function from one function. Functools. partial returns a partial object using partial(func, *args, **kw), where func is mandatory and at least one arg or kw argument is required.Copy the code

<1>demo1, the function has only one input parameter

Def addOne (x) def addOne (x) def addone(x) def addone(x) Return x+1 result = addone(3) print(result) If we build a new function from addone(), the name of this new function is add def addone(x): Return x+1 add = functools.partial(addone,3) # Add print(add()) Where did this 4 come from? Add = functools.partial(addone, 3) defines a new variable add, which is the result of addone(3). When add() is executed, It's actually addone(3), it's the result of addone(3), and the 4 that this add() function returns is the result of addone(3), so that's where this 4 came from.Copy the code

<2>demo2, the function has two inputs

Here is a slightly more complicated example: the addone() function above had only one input parameter. We now addone more input parameter to return the sum of the two parameters. def sum(x,y): Return x+y resutl = sum(5,6) print(result) sumy = functools.partial(sum,5) print(sumy(6)) Print (sum(5, 6)) print(sumY(6)) print(sum(5, 6)) print(sumY(6)) 11 Sumy = functools.partial(sum, y) {sum(x, y) = functools.partial(sum, y) {sum(x, y) = functools.partial(sum, y) Instead of passing in an x argument, the sumy function is fixed to 5. Kwargs arguments How do you define partial functions when you have k,v?Copy the code

<3>demo3, the function has three inputs

Def add(x,y,z): return x+y+z p = functools.partial(add, 12) def add(x,y,z): return x+y+z p = functools. When p is called, just pass in the y and z arguments because x is already fixed. Calling this new function p print(p(1,2)) yields 15Copy the code

<4>demo4, the parameter of the function is of the form KV

def show(name="yyx",age=100): Return (name,age) showp = functools.partial(show,age=5) print(showp('zhangsanfeng')) If age=18, show(name="yyx", age=18) Age =18 (yangyanxing); age=18 (yangyanxing); Showp (" yangyanxing ", 28) is an error if age is added.Copy the code

Functools.partial () What is functools.partial()?

From the previous demos, it seems that using functools.partial doesn't work either, just fixing the value of an argument and passing one less argument to the original call, but we might have a function scenario where the argument is a function, such as a callback function.Copy the code