Operator Overloading in Python


Python Clean Code Tip:

Use operator overloading to enable usage of operators such as +, -, /, *, ... on your instances.

👇

from dataclasses import dataclass


# without operator overloading
@dataclass
class TestDrivenIOCoin:
    value: float

    def add(self, other):
        if not isinstance(other, TestDrivenIOCoin):
            return NotImplemented

        return TestDrivenIOCoin(value=self.value + other.value)


my_coins = TestDrivenIOCoin(value=120).add(TestDrivenIOCoin(value=357.01))
print(my_coins)
# TestDrivenIOCoin(value=477.01)


# with operator overloading
@dataclass
class TestDrivenIOCoin:
    value: float

    def __add__(self, other):
        if not isinstance(other, TestDrivenIOCoin):
            return NotImplemented

        return TestDrivenIOCoin(value=self.value + other.value)


my_coins = TestDrivenIOCoin(value=120) + TestDrivenIOCoin(value=357.01)
print(my_coins)
# TestDrivenIOCoin(value=477.01)