# In python, everything is an object from a class
# We can define our own classes
from math import sqrt
class Vector():
# custom type for 2d vectors
# class attribute shared by all objects of this class
dim = 2
def __init__(self, input_x, input_y):
# constructor, called when new object is created, Vector(x,y)
# self is the object being created
# .x and .y are object attributes
self.x = input_x
self.y = input_y
def length(self):
# length method, returns length of vector
l = sqrt(self.x**2+self.y**2)
return l
def scale(self, c):
# method that scales the vector by a constant c
# changes the object itself
# no return value, so returns None
self.x = self.x * c
self.y = self.y * c
def __repr__(self):
# string representation of the object
# without this method, it prints the memory address
return f'({self.x},{self.y})'
def add(self, other_vector):
# method that adds another vector to this vector, returns new vector
x_new = self.x + other_vector.x
y_new = self.y + other_vector.y
return Vector(x_new, y_new)
def __add__(self, other_vector):
# special method that overloads the + operator
# without this method, vector + vector would raise an error
x_new = self.x + other_vector.x
y_new = self.y + other_vector.y
return Vector(x_new, y_new)
def normalize(self):
# method that scales the vector to unit length
# can call other methods of the same object
l = self.length()
self.scale(1/l)