The Python partial() function allows us to create a new function with a specific number of arguments predefined from another function. A partial() function is used to specify a function by reducing the number of parameters it requires. This defining by constant values for the particular number of arguments. It makes the code more reusable without specifying the original function.
SyntaxFollowing is the syntax for the partial() function.
functools.partial(func, /, *args, **kwargs)Parameters
The parameters for the partial() function are listed below −
This function returns a new object, that behaves like the original function with specified number of arguments.
Example 1In the below example we are creating a specific version to multiply the arguments that are predefined using the partial() function.
from functools import partial def multiply(n, p): return n*p x = partial(multiply, 3) print(x(3))Output
The result is generated as follows −
9Example 2
Here, partial() is used to create a new function and this calculates a result that is based on the formula below.
from functools import partial def func(m, n, o, p): return m*1 + n*2 + o*3 + p x = partial(func, 4, 5, 6) print(x(7))Output
The code is generated as follows −
39Example 3
In the example below, we are using the predefined values for x and y, while add function takes a single argument, which is the variable z.
from functools import * def add(w, x, y): return 1000*w + 100*x + y add_part = partial(add, y = 3, x = 2) print(add_part(2))Output
The output is obtained as follows −
2203
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4