WEEK 5 LESSON 3 OF 5

Operator Overloading

Make +, ==, print(), and len() work with your own classes using special "dunder" methods.

What Are Dunder Methods?

"Dunder" stands for double underscore. Methods like __init__, __str__, and __add__ are special methods that Python calls behind the scenes when you use operators or built-in functions.

When you write a + b, Python actually calls a.__add__(b). By defining these methods in your class, you control how operators behave with your objects.

__str__: How print() Displays Your Object

Without __str__, printing an object gives you something ugly like <__main__.Product object at 0x...>. Define __str__ to control that.

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f"{self.name}: ${self.price:.2f}"

p = Product("Laptop", 999)
print(p)  # Laptop: $999.00

__add__: Make + Work

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 __str__(self):
        return f"({self.x}, {self.y})"

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)  # (4, 6)

How it works: When Python sees v1 + v2, it calls v1.__add__(v2). Our method creates and returns a new Vector with the combined values.

__eq__ and __lt__: Comparison Operators

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def __eq__(self, other):
        return self.grade == other.grade

    def __lt__(self, other):
        return self.grade < other.grade

    def __str__(self):
        return f"{self.name} (grade: {self.grade})"

s1 = Student("Alice", 92)
s2 = Student("Bob", 85)
s3 = Student("Carol", 92)

print(s1 == s3)  # True  (same grade)
print(s2 < s1)   # True  (85 < 92)

# Sorting works automatically with __lt__
students = [s1, s2, s3]
students.sort()
for s in students:
    print(s)

__len__: Make len() Work

class Playlist:
    def __init__(self, name):
        self.name = name
        self.songs = []

    def add(self, song):
        self.songs.append(song)

    def __len__(self):
        return len(self.songs)

p = Playlist("Road Trip")
p.add("Bohemian Rhapsody")
p.add("Hotel California")
print(len(p))  # 2

Common Dunder Methods

MethodTriggered ByPurpose
__str__print(obj), str(obj)Human-readable string
__repr__repr(obj), debuggerDeveloper-readable string
__add__a + bAddition
__eq__a == bEquality check
__lt__a < b, sortingLess-than comparison
__len__len(obj)Length / size

Best Practices

  • Always define __str__ for any class you might print -- it makes debugging so much easier.
  • Return a new object from __add__ rather than modifying self -- just like how 1 + 2 gives a new number.
  • Only overload operators when the behavior is intuitive (adding vectors makes sense; adding users does not).

Common Mistakes

  • Forgetting to return a value from __add__ -- without a return, the result is None.
  • Confusing __str__ (for users) with __repr__ (for developers). Define both when appropriate.
  • Overloading operators in ways that are confusing or unexpected to other programmers.

Practice Exercises

Exercise 1: Money Class

Create a Money class with __add__, __str__, and __eq__. Adding two Money objects should return a new one with the combined amounts.

Exercise 2: Shopping Cart

Create a Cart class where len(cart) returns the number of items and print(cart) shows all items.

Exercise 3: Temperature

Create a Temperature class with __lt__, __eq__, and __str__. Create a list of temperatures and sort them.

Summary

  • Operator overloading lets you define how +, ==, <, print(), and len() work with your classes.
  • Dunder methods (__str__, __add__, __eq__, __lt__, __len__) are the mechanism behind it.
  • Always return a new object from __add__ and keep overloads intuitive.
  • This is another form of polymorphism -- same operator, different behavior per class.