Skip to content

Module 11 · Object-Oriented Programming — topic 24 of 25

Special methods

Dunder methods that integrate classes with Python's syntax: __str__ and __repr__, comparison (__eq__, __lt__), arithmetic (__add__, __mul__), and container protocols (__len__, __getitem__, __contains__, __iter__, __bool__).

Beginner 12 min read·Lesson 181 of 306 in Python Programming

Learning objectives

  • Implement __str__ and __repr__
  • Overload operators and comparisons
  • Make a class behave like a container

Definition

Special methods (also called magic or dunder methods) have names with double underscores, such as __len__ and __add__. Python calls them automatically for built-in operations, letting your objects work with len(), +, ==, in, for loops and print.

Introduction

Why does len(my_list) work, and why can you write a + b for strings? Because list defines __len__ and str defines __add__. Your own classes can do the same.

Why it matters

Special methods make your classes feel built in. A Vector that supports + and a Playlist that supports len and in are easier to use than ones with custom method names.

Detailed explanation

__repr__ returns an unambiguous developer view (ideally valid Python like Point(2, 3)); __str__ returns a friendly view for print. If only __repr__ exists, print uses it.

Comparison: __eq__ powers ==; __lt__, __le__, __gt__ and __ge__ power the ordering operators and let sorted() work. functools.total_ordering can fill in the rest from __eq__ and __lt__.

Arithmetic: __add__, __sub__, __mul__ and friends implement +, -, *. Return NotImplemented for unsupported types so Python can try the other operand.

Containers: __len__ for len(), __getitem__ for indexing and slicing, __contains__ for in, __iter__ for loops, and __bool__ for truth testing.

__init__ itself is a special method; others include __call__ (make instances callable) and __enter__/__exit__ (with statements).

Defining __eq__ without __hash__ makes instances unhashable, so they can't be set members or dict keys unless you also define __hash__.

Syntax

Python
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
  • Python calls dunder methods for operators and built-ins.
  • __repr__ for developers, __str__ for users.
  • Return NotImplemented for unsupported types.

Code examples

__str__ and __repr__

Python
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(2, 3)
print(p)
print(repr(p))
print([p, Point(0, 0)])
Output
(2, 3)
Point(2, 3)
[Point(2, 3), Point(0, 0)]

Operators and equality

Python
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, k):
return Vector(self.x * k, self.y * k)
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
a, b = Vector(1, 2), Vector(3, 4)
print(a + b, a * 3, a + b == Vector(4, 6))
Output
Vector(4, 6) Vector(3, 6) True

More examples

A container-like class

Python
class Playlist:
def __init__(self, name, songs):
self.name = name
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __getitem__(self, i):
return self._songs[i]
def __contains__(self, song):
return song.lower() in (s.lower() for s in self._songs)
def __iter__(self):
return iter(self._songs)
def __bool__(self):
return bool(self._songs)
def __repr__(self):
return f"Playlist({self.name!r}, {len(self)} songs)"
pl = Playlist("Focus", ["Weightless", "Clair de Lune", "Experience"])
print(pl, len(pl))
print(pl[0], pl[-1])
print("clair de lune" in pl)
print([s.upper() for s in pl][:2])
print(bool(Playlist("Empty", [])))
Output
Playlist('Focus', 3 songs) 3
Weightless Experience
True
['WEIGHTLESS', 'CLAIR DE LUNE']
False

Step-by-step explanation

  • __len__ and __getitem__ make len(pl) and pl[0] work, including negative indexes.
  • __contains__ customises in to ignore case.
  • __iter__ lets the playlist be used in for loops and comprehensions; __bool__ makes an empty playlist falsy.

Expected output

Running “A container-like class” prints exactly:

TextOutput
Playlist('Focus', 3 songs) 3
Weightless Experience
True
['WEIGHTLESS', 'CLAIR DE LUNE']
False

Practical applications

  • pathlib uses __truediv__ so paths can be joined with /.
  • Decimal and Fraction overload arithmetic operators.

Best practices

  • Always define a useful __repr__.
  • Implement only the special methods that make sense for the type.
  • Keep operator meanings intuitive.

Common mistakes

Calling dunder methods directly

Avoid

v1.__add__(v2)

Prefer

v1 + v2

Use the operator or built-in; Python handles the protocol details.

Returning a string from __len__

Avoid

def __len__(self):
return "3"

Prefer

def __len__(self):
return 3

__len__ must return a non-negative int, otherwise len() raises TypeError.

Important notes

  • @dataclass generates __init__, __repr__ and __eq__ automatically.

Key takeaways

  • Special methods connect classes to Python syntax.
  • __repr__/__str__ control display; __eq__/__lt__ control comparison.
  • __len__, __getitem__, __iter__, __contains__ make container-like classes.

Try it yourself

  1. 1
    Add __sub__ and __abs__ (length) to the Vector class.
  2. 2
    Make a Money class that supports +, == and < and refuses to add different currencies.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this topic