Extra Topic: Special Methods


Note: extra topics are not in CS Academy, but are required and can appear on any future homework, writing session, quiz, or exam.
Getting Started
Example: A basic Vector class:

class Vector: def __init__(self, dx, dy): self.dx = dx self.dy = dy def __repr__(self): return f'Vector({self.dx}, {self.dy})' def __eq__(self, other): return (isinstance(other, Vector) and self.dx == other.dx and self.dy == other.dy) def __hash__(self): return hash((self.dx, self.dy)) v1 = Vector(2, 3) print(v1) # Vector(2, 3) print(v1 == Vector(2, 3)) # True print(v1 == Vector(2, 4)) # False

Making + work with Vector instances (using __add__):

class Vector: def __init__(self, dx, dy): self.dx = dx self.dy = dy def __repr__(self): return f'Vector({self.dx}, {self.dy})' def __eq__(self, other): return (isinstance(other, Vector) and self.dx == other.dx and self.dy == other.dy) def __hash__(self): return hash((self.dx, self.dy)) def __add__(self, other): assert(isinstance(other, Vector)) return Vector(self.dx + other.dx, self.dy + other.dy) v1 = Vector(2, 3) v2 = Vector(2, 4) v3 = v1 + v2 print(v3) # Vector(4, 7)

Making < work with Vector instances (using __lt__):

class Vector: def __init__(self, dx, dy): self.dx = dx self.dy = dy def __repr__(self): return f'Vector({self.dx}, {self.dy})' def __eq__(self, other): return (isinstance(other, Vector) and self.dx == other.dx and self.dy == other.dy) def __hash__(self): return hash((self.dx, self.dy)) def __add__(self, other): assert(isinstance(other, Vector)) return Vector(self.dx + other.dx, self.dy + other.dy) def __lt__(self, other): assert(isinstance(other, Vector)) return self.magnitude() < other.magnitude() def magnitude(self): return (self.dx**2 + self.dy**2)**0.5 v1 = Vector(2, 3) v2 = Vector(2, 4) print(v1 < v2) # True print(v2 < v1) # False print(Vector(3, 4) < Vector(4, 3)) # False print(Vector(4, 3) < Vector(3, 4)) # False