Introduction
Magic methods (dunder methods) allow custom behavior for built-in operations.
Comparison Methods
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __lt__(self, other):
return (self.x ** 2 + self.y ** 2) < (other.x ** 2 + other.y ** 2)
def __le__(self, other):
return self == other or self < other
Arithmetic Operators
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
Container Methods
class Queue:
def __init__(self):
self.items = []
def __len__(self):
return len(self.items)
def __contains__(self, item):
return item in self.items
def __iter__(self):
return iter(self.items)
Practice Problems
- Implement comparison for fraction class
- Create custom list with arithmetic operations
- Add len and bool to a class
- Implement call to make object callable
- Create a string representation for debugging