Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python functools partialmethod() Function



The Pythonpartialmethod() function is similar to the partial function. The main difference is partialmethod() is used within the class method.

The 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.

Syntax

Following is the syntax for thepartialmethod() function.

functools.partialmethod(func, /, *args, **keywords)

Parameters

The parameters for thepartialmethod() 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.
  • **keywords : This is the keyword argument used to predefined the new function.

Return Value

This function returns a new partial method descriptor.

Example 1

In the below example, we double the given values by multiplying the predefined values using thepartialmethod() function.

import functoolsclass Calculator:    def multiply(x, y, z):       return y*z    double = functools.partialmethod(multiply, 4)a = Calculator()print(a.double(10))print(a.double(20))

Output

The result is generated as follows −

4080

Example 2

This code defines the Adder class with an add method that sums three numbers using thepartialmethod() function. The add_ten method pre fills the first argument with 10, with the remaining arguments provided during the method call.

import functoolsclass Adder:    def add(self, x, y, z):        return x + y + z    add_ten = functools.partialmethod(add, 10)adder = Adder()print(adder.add_ten(10, 20))  print(adder.add_ten(15, 25))

Output

The code is generated as follows −

4050

Example 3

Here, we are defining the power class with power method that rises a base to an exponent. When square is called usingpartialmethod() function then it returns the square of the given number.

import functoolsclass Power:  def power(self, base, exponent):    return base**exponent  square = functools.partialmethod(power, exponent = 4)power = Power()print(power.square(16))print(power.square(8))

Output

The output is obtained as follows −

655364096
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp