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)
'Python' 카테고리의 다른 글
Python 클로져 함수(Closure Function) (0) | 2024.03.29 |
---|---|
Python 패킹(packing) 언패킹(unpacking) 총정리 (0) | 2024.03.29 |
Python 제너레이터(Generator) (0) | 2024.03.29 |
Python 연결 리스트(Linked List) (0) | 2024.03.29 |
Python 싱글턴 패턴(Singleton Pattern), 반복자 패턴(Iterator Pattern), 데코레이터 패턴(Decorator Pattern) (0) | 2024.03.29 |