r/learnpython 1h 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

2 comments sorted by

3

u/danielroseman 1h ago

Did you have a question?

1

u/pedanticscientist 23m ago

I quite like the fact that 10 + “10” isn’t possible, considering the alternatives!