본문 바로가기

Python

Python 연산자 오버로딩을 위한 스페셜 메서드 정리

728x90

연산자 오버로딩이란?

연산자 오버로딩(Operator overloading)이란, 사용자 정의 클래스에서 기존에 정의된 연산자(+, -, *, / 등)의 동작을 재정의하는 것을 말한다. 이를 통해 사용자 정의 데이터 타입에 대해 연산자를 사용하여 직관적으로 작업할 수 있다.

 

class Number:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)
    
    def __add__(self, other):
        if isinstance(other, Number):
            return Number(self.value + other.value)
        
        if isinstance(other, (int, float, bool)):
            return Number(self.value + other)
    
    def __sub__(self, other):
        if isinstance(other, Number):
            return Number(self.value - other.value)
        
        if isinstance(other, (int, float, bool)):
            return Number(self.value - other)
        
    def __mul__(self, other):
        if isinstance(other, Number):
            return Number(self.value * other.value)
        
        if isinstance(other, (int, float, bool)):
            return Number(self.value * other)
        
    def __truediv__(self, other):
        if isinstance(other, Number):
            return Number(self.value / other.value)
        
        if isinstance(other, (int, float, bool)):
            return Number(self.value / other)        
        
    def __radd__(self, other): # right add
        if isinstance(other, (int, float, bool)):
            return Number(self.value + other)
        
    def __rmul__(self, other):      
        if isinstance(other, (int, float, bool)):
            return Number(self.value * other)
    
    
    
        
numObj = Number(3)
numObj2 = Number(6)
print(numObj.value)
print(numObj + numObj2) # Number.__add__(numObj)
print(numObj + 1) # Number.__add__(numObj)
print(numObj + 3.3) # Number.__add__(numObj)
print(numObj + True) # Number.__add__(numObj)

print(1 + numObj) # (1).__add__(numObj) ---fail---> n1.__radd__(1)
print(numObj / 4) # Number.__truediv__(numObj)
print(3 * numObj) # Number.__mul__(numObj)