[Python]매직 메서드(magic method, special method)
파이썬의 Magic Method(Special Method)에 대해 알아보자
class Vector(object): ''' 2개의 좌표를 가진 벡터를 만드는 클래스 ''' def __init__(self, *args): ''' 사용예제 : v = Vector(1, 3) ''' if len(args) == 0: self._x, self._y = 0, 0 else: self._x, self._y = args def __repr__(self): return f'Vector({self._x}, {self._y})' def __add__(self, other): return Vector(self._x + other._x, self._y + other._y) def __mul__(self, other): return Vector(self._x * other, self._y * other) def __bool__(self): '''x, y가 0, 0 이면 False, 그 외에는 True가 반환된다.''' return bool(max(self._x, self._y)) print(Vector.__doc__) print(Vector.__init__.__doc__) a = Vector(1, 5) b = Vector() c = Vector(2, 3) print(a) print(b) print(a + c) print(a * 3) print(bool(b)) ''' 출력결과 2개의 좌표를 가진 벡터를 만드는 클래스 사용예제 : v = Vector(1, 3) Vector(1, 5) Vector(0, 0) Vector(3, 8) Vector(3, 15) False '''
최신 댓글