Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python functools partial() Function



The Pythonpartial() 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.

Syntax

Following is the syntax for thepartial() function.

functools.partial(func, /, *args, **kwargs)

Parameters

The parameters for thepartial() function are listed below −

  • / : This indicates that all parameters must be specified positionally.
  • *args : This is the positional argument used to set in advance for the new function.
  • **kwargs : This is the keyword argument used to predefined the new function.

Return Value

This function returns a new object, that behaves like the original function with specified number of arguments.

Example 1

In the below example we are creating a specific version to multiply the arguments that are predefined using thepartial() function.

from functools import partialdef multiply(n, p):    return n*px = partial(multiply, 3)print(x(3))

Output

The result is generated as follows −

9

Example 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 partialdef func(m, n, o, p):    return m*1 + n*2 + o*3 + px = partial(func, 4, 5, 6)print(x(7))

Output

The code is generated as follows −

39

Example 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 + yadd_part = partial(add, y = 3, x = 2)print(add_part(2))

Output

The output is obtained as follows −

2203
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp