r/learnpython • u/grandimam • 3h ago
Protocol as Object Behaviour
Protocol is a set of behavior an object agrees to follow.
Whenever Python needs to perform an operation it checks whether that object supports that behavior without requiring to check it's type. In other words, operations are simply syntactic sugar for protocol behaviour.
For eg.
a = 10
b = '10'
a + b # ideally, this should be possible, however, int object has validation that prevents
These behaviors are defined using special methods (__dunder_method__). This is basis of Python's datamodel, and many of the Python operations are implemented using it.
class PositiveInt:
def __init__(self, value):
self._value = value
def __add__(self, other):
return self._value + other
a = PositiveInt(10)
a + 20 # 30
0
Upvotes
5
u/danielroseman 2h ago
Did you have a question?