매직 메서드 - 수치와 산술 연산
1. 단항 연산자
파이썬에서는 -
, +
, abs()
같은 단항 연산자를 위한 매직 메서드를 제공합니다.
class Number:
def __init__(self, value):
self.value = value
def __neg__(self): # -n
return Number(-self.value)
def __pos__(self): # +n
return Number(self.value)
def __abs__(self): # abs(n)
return Number(abs(self.value))
def __str__(self):
return str(self.value)
n = Number(5)
print(f"원본: {n}") # 5
print(f"음수: {-n}") # -5
print(f"양수: {+n}") # 5
print(f"절대값: {abs(n)}") # 5
n = Number(-3)
print(f"절대값: {abs(n)}") # 3
2. 이항 산술 연산자
두 개의 피연산자를 사용하는 기본적인 산술 연산자들입니다.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # self + other
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other): # self - other
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, scalar): # self * scalar
return Point(self.x * scalar, self.y * scalar)
def __str__(self):
return f"Point({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(3, 4)
print(f"더하기: {p1 + p2}") # Point(4, 6)
print(f"빼기: {p2 - p1}") # Point(2, 2)
print(f"곱하기: {p1 * 3}") # Point(3, 6)
나머지 연산자는 아래와 같습니다.
__add__
: x + y 덧셈 연산을 정의
__sub__
: x - y 뺄셈 연산을 정의
__mul__
: x * y 곱셈 연산을 정의
__truediv__
: x / y 나눗셈 연산을 정의
__floordiv__
: x // y 몫 연산을 정의
__mod__
: x % y 나머지 연산을 정의
__pow__
: x ** y 거듭제곱 연산을 정의
3. 복합 할당 연산자
+=
, -=
같은 복합 할당 연산자는 별도의 매직 메서드를 사용합니다. 여기서 앞에 i
는 in-place
를 의미합니다.
class Counter:
def __init__(self, value):
self.value = value
def __iadd__(self, other): # self += other
self.value += other
return self
def __isub__(self, other): # self -= other
self.value -= other
return self
def __str__(self):
return str(self.value)
c = Counter(10)
print(f"처음: {c}") # 10
c += 5
print(f"더하기: {c}") # 15
c -= 3
print(f"빼기: {c}") # 12
나머지 연산자는 아래와 같습니다.
__iadd__
: x += y 복합 덧셈 할당
__isub__
: x -= y 복합 뺄셈 할당
__imul__
: x *= y 복합 곱셈 할당
__itruediv__
: x /= y 복합 나눗셈 할당
__ifloordiv__
: x //= y 복합 몫 할당
__imod__
: x %= y 복합 나머지 할당
__ipow__
: x **= y 복합 거듭제곱 할당
4. 비교 연산자
<
, >
, ==
같은 비교 연산자도 구현할 수 있습니다.
class Grade:
def __init__(self, score):
self.score = score
def __lt__(self, other): # self < other
return self.score < other.score
def __eq__(self, other): # self == other
return self.score == other.score
def __str__(self):
return f"Grade({self.score})"
math = Grade(85)
science = Grade(90)
print(f"수학 < 과학: {math < science}") # True
print(f"수학 == 과학: {math == science}") # False
나머지 연산자는 아래와 같습니다.
__lt__
: x < y (less than) 작음을 비교
__le__
: x <= y (less than or equal) 작거나 같음을 비교
__gt__
: x > y (greater than) 큼을 비교
__ge__
: x >= y (greater than or equal) 크거나 같음을 비교
__eq__
: x == y (equal) 같음을 비교
__ne__
: x != y (not equal) 다름을 비교
5. 실제 활용 예시
실제 프로그램에서 사용할 수 있는 예시입니다. 가장 자주 사용하는 class
자료형에 수학 수식을 적용하면 어떨지를 먼저 상상해보고 적용하는 것을 권합니다. 수학수식이 필요하지 않은 경우도 있습니다.
class Book:
def __init__(self, name, price):
self.name = name
self.price = price
def __add__(self, other):
return self.price + other.price
def __sub__(self, other):
return self.price - other.price
def __mul__(self, count):
return self.price * count
def __str__(self):
return f"Book({self.name}, {self.price})"
book1 = Book("파이썬", 10000)
book2 = Book("자바", 15000)
print(f"더하기: {book1 + book2}") # Book(25000) {"packages":["numpy","pandas","matplotlib","lxml"]}