In Python, we use the functools
module to create higher-order functions that interact with other functions. The higher-order functions either return other functions or operate on them to broaden the function’s scope without modifying or explicitly defining them.
The partialmethod()
method is similar to [partial()
](https://www.educative.io/shoteditor/4892716999114752. The only difference is that we use it as a method definition in class.
Below is an example that uses partialmethod()
from the functools
module.
from functools import partialmethodclass Switch:def __init__(self):self._state = Falsedef set_new_state(self, new_state: bool):self._state = new_state@propertydef state(self):return self._stateturn_on = partialmethod(set_new_state, True)turn_off = partialmethod(set_new_state, False)switch = Switch()print("Turning on the switch: ", end="")switch.turn_on()print(switch.state)print("Turning off the switch: ", end="")switch.turn_off()print(switch.state)
partialmethod
from the functools
module.Switch
class that contains _state
as the attribute.__init__
method, which sets the _state
attribute to False
by default when a new instance of Switch
is created.set_new_state
instance method where we can set a new state to the Switch
object.partialmethod
descriptors, turn_on
and turn_off.
These descriptors will internally call the set_new_state()
method with True
or False.
Using these descriptors, we can set the state of the Switch
instance.Switch
class is created, and the state is turned on and off using the turn_on
and turn_off
descriptors.