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.
SyntaxFollowing is the syntax for the partialmethod() function.
functools.partialmethod(func, /, *args, **keywords)Parameters
The parameters for the partialmethod() function are listed below −
This function returns a new partial method descriptor.
Example 1In 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 80Example 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 50Example 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
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