카테고리 없음

Python arithmetic overloading

SciomageLAB 2024. 10. 4. 12:10
반응형

궁금한 것

파이썬에서 오버로딩을 구현할 때 누구의 오버로딩이 먼저 발생하는지 궁금

예상

A + B의 경우 연산이 좌->우로 가기 때문에 A의 오버로딩이 먼저 발생할 것

검증 코드

class A:
    val = [1, 2, 3]

    def __add__(self, other):
        if isinstance(other, B):
            print("A's overloading")
            return other.val[1] + self.val[1]

class B:
    val = [2, 3, 4]

    def __add__(self, other):
        if isinstance(other, A):
            print("B's overloading")
            return other.val[0] + self.val[0]


if __name__ == "__main__":
    a = A()
    b = B()

    print(a + b)
    print(b + a)

결과

A's overloading
5
B's overloading
3

다른 케이스

좌측에 오는 오브젝트가 오버로딩이 안 되어있을 경우

class A:
    val = [1, 2, 3]

    def __add__(self, other):
        if isinstance(other, B):
            print("A's overloading")
            return other.val[1] + self.val[1]

        elif isinstance(other, int):
            print(other)
            return self.val[-1] + other


class MyInt(int):
    def __init__(self, val):
        self.val = val

    def __add__(self, other):
        return other + self.val

결과

Traceback (most recent call last):
  File "/home/dsparch/KIRO/BasicML/arith_overload.py", line 36, in <module>
    print(2 + a)
          ~~^~~
TypeError: unsupported operand type(s) for +: 'int' and 'A'

방법

primitive에 가까울 수록 연산의 순서를 변경하여 구현

예를 들어 int 같은 경우 다른 오브젝트들이 어떤 식으로 오버로딩이 되어 있는지 모르니 이를 다 대응해주는 케이스로 짜기 보다 본인이 연산 순서를 후위로 가서 other 오브젝트의 오버로딩이 불리는 방향으로 구현

    def __add__(self, other):
        return other + self.val
반응형