사소한 TIL:

Python에서a + b를 실행하면 a.__add__(b)를 먼저 시도하고, NotImplemented를 반환하면 b.__radd__(a)를 시도한다.

단, Python 2.2 이상에선 b가 a의 서브클래스이면 순서가 뒤집혀서 b.__radd__(a)를 먼저 호출한다.
이 규칙이 없으면 A.__add__가 먼저 동작해서, 서브클래스가 오른쪽에 있을 때 override를 못하기 때문이다. (cpython 코드)

단, 서브클래스가 __radd__를 직접 정의하지 않고 상속만 한 경우에는 뒤집지 않는다.

class A:
    def __add__(self, other):
        return "A.__add__"

class B(A):
    def __radd__(self, other):
        return "B.__radd__"

A() + B()  # B.__radd__ — 서브클래스의 radd가 먼저 호출됨
2

If you have a fediverse account, you can reply to this note from your own instance. Search https://hackers.pub/ap/notes/019ce300-9027-7a39-bf03-effd93c91087 on your instance and reply to it.