from math import hypot
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self): # 객체를 문자열로 표현
return 'Vector({!r}, {!r})'.format(self.x, self.y)
def __abs__(self):
return hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __rmul__(self, scalar): # scalar가 왼쪽에 오는 곱셈을 가능케 해줌
return Vector(self.x * scalar, self.y * scalar)
>>> b = Vector(1,2)
>>> a = Vector(3,4)
>>> a+b
Vector(4, 6)
>>> a*3
Vector(9, 12)
>>> abs(a)
5.0
>>> bool(a)
True