Partial class

A partial function is an original function for particular argument values. They can be created in Python by using “partial” from the functools library. The __name__ and __doc__ attributes are to be created by the programmer as they are not created automatically. Objects created by partial() have three read-only attributes: Syntax:

partial(func, /, *args, **keywords)
  • partial.func – It returns the name of parent function along with hexadecimal address.
  • partial.args – It returns the positional arguments provided in partial function.
  • partial.keywords – It returns the keyword arguments provided in partial function.

Example: 

Python3




from functools import partial
 
 
def power(a, b):
    return a**b
 
 
# partial functions
pow2 = partial(power, b=2)
pow4 = partial(power, b=4)
power_of_5 = partial(power, 5)
 
print(power(2, 3))
print(pow2(4))
print(pow4(3))
print(power_of_5(2))
 
print('Function used in partial function pow2 :', pow2.func)
print('Default keywords for pow2 :', pow2.keywords)
print('Default arguments for power_of_5 :', power_of_5.args)


Output

8
16
81
25
Function used in partial function pow2 : <function power at 0x7f8fcae38320>
Default keywords for pow2 : {'b': 2}
Default arguments for power_of_5 : (5,)

Functools module in Python

Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes – partial and partialmethod.

Similar Reads

Partial class

A partial function is an original function for particular argument values. They can be created in Python by using “partial” from the functools library. The __name__ and __doc__ attributes are to be created by the programmer as they are not created automatically. Objects created by partial() have three read-only attributes: Syntax:...

Partialmethod class

...

Functions

It is a method definition of an already defined function for specific arguments like a partial function. However, it is not callable but is only a method descriptor. It returns a new partialmethod descriptor....