Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python functools partialmethod() Function



The Python partialmethod() 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 the partialmethod() function.

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

Parameters

The parameters for the partialmethod() 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 the partialmethod() function.

import functools
class 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 −

40
80

Example 2

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

import functools
class 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 −

40
50

Example 3

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

import functools
class 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 −

65536
4096
python_modules.htm
Advertisements