Skip to content

Instantly share code, notes, and snippets.

@Aditya1001001
Last active July 24, 2021 01:06
Show Gist options
  • Save Aditya1001001/badc5f9f25c8b74b30fb6fb08e7b8136 to your computer and use it in GitHub Desktop.
Save Aditya1001001/badc5f9f25c8b74b30fb6fb08e7b8136 to your computer and use it in GitHub Desktop.
An example vector class for illustrating useful dunder methods.
class Vector():
def __new__(cls, x, y):
print("__new__ was invoked")
instance = object.__new__(cls)
return instance
def __init__(self, x, y):
print("__init__ was invoked")
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __str__(self):
return f"{self.x}x + {self.y}y"
def __len__(self):
return int((self.x*self.x +self.y*self.y)**(1/2))
def __getitem__(self, key):
if key < 0 or key > 1:
raise IndexError("Index out of range! Should either be 0 or 1.")
elif key:
return self.y
else:
return self.x
def __setitem__(self, key, val):
if key < 0 or key > 1:
raise IndexError("Index out of range! Should either be 0 or 1.")
elif key:
self.y = val
else:
self.x = val
def __call__(self):
print(f"Vector({self.x}, {self.y}) was called.")
return (self.x*self.x +self.y*self.y)**(1/2)
def __add__(self, other):
if type(other) is not Vector:
raise TypeError('other should be an object of class Vector')
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
if type(other) is not Vector:
raise TypeError('other should be an object of class Vector')
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, other):
if type(other) is not Vector:
raise TypeError('other should be an object of class Vector')
return self.x * other.x + self.y * other.y
def __lt__(self, other):
if type(other) is not Vector:
raise TypeError('other should be an object of class Vector')
return self() < other()
def __gt__(self, other):
if type(other) is not Vector:
raise TypeError('other should be an object of class Vector')
return self() > other()
def __eq__(self, other):
if type(other) is not Vector:
raise TypeError('other should be an object of class Vector')
return self.x == other.x and self.y == other.y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment