반응형
#1 연산자 오버라이딩
init처럼 클래스를 만들 때 정해진 기능을 할 수 있도록 미리 정해진 특별한 메서드들이 있다. 연산자들도 내부적으로는 특별한 메서드로 구현되어 있다. 기본자료형처럼 객체에 연산자를 사용하고 싶으면 특별한 이름을 가진 메서드들을 만들면 된다.
x = int(1)
y = int(3)
a = x + y
#a = x.__add__(y)
print(a)
벡터 자료형이다. 사용자정의 자료형이기 때문에 벡터 간에 덧셈 연산이 정의되어 있지 않다.
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
v1 = Vector2D(1, 2)
v2 = Vector2D(3, 4)
v3 = v1 + v2 # ???
아래와 같이 연산자 오버라이딩을 하면 기본연산자로 사용자 정의 자료형 간에 연산할 수 있다.
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, v):
return Vector2D(self.x + v.x, self.y + v.y)
v1 = Vector2D(1, 2)
v2 = Vector2D(3, 4)
v3 = v1 + v2 # v1.__add__(v2)
print(v3.x, v3.y)
print(v3) # ???
#2 연산자와 매직메서드
이항연산자
| Operator | Magic Method |
|---|---|
| + | __add__(self, other) |
| – | __sub__(self, other) |
| * | __mul__(self, other) |
| / | __truediv__(self, other) |
| // | __floordiv__(self, other) |
| % | __mod__(self, other) |
| ** | __pow__(self, other) |
| >> | __rshift__(self, other) |
| << | __lshift__(self, other) |
| & | __and__(self, other) |
| ^ | __xor__(self, other) |
비교연산자
| Operator | Magic Method |
|---|---|
| < | __lt__(self, other) |
| > | __gt__(self, other) |
| <= | __le__(self, other) |
| >= | __ge__(self, other) |
| == | __eq__(self, other) |
| != | __ne__(self, other) |
대입연산자
| Operator | Magic Method |
|---|---|
| -= | __isub__(self, other) |
| += | __iadd__(self, other) |
| *= | __imul__(self, other) |
| /= | __idiv__(self, other) |
| //= | __ifloordiv__(self, other) |
| %= | __imod__(self, other) |
| **= | __ipow__(self, other) |
| >>= | __irshift__(self, other) |
| <<= | __ilshift__(self, other) |
| &= | __iand__(self, other) |
| ** | =** |
| ^= | __ixor__(self, other) |
단항연산자
| Operator | Magic Method |
|---|---|
| – | __neg__(self) |
| + | __pos__(self) |
| ~ | __invert__(self) |
반응형