Functions and Objects · Objects · lesson 9 of 10
Dunder methods
about 15 minutes · free · runs in your browser
Making your objects behave like built-in ones
Methods named with double underscores — "dunder" methods — hook your class into Python's own syntax.
| Method | Called by |
|---|---|
__init__ | creating an instance |
__str__ | print(obj) and str(obj) |
__repr__ | the console, and debugging |
__eq__ | a == b |
__len__ | len(obj) |
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"({self.x}, {self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y
Without __eq__, Point(1, 2) == Point(1, 2) is False — Python falls back to
comparing identity, and they are two different objects.
Your turn: give Playlist a __str__ reading "Road Trip (3 tracks)", a
__len__ returning the track count, and an __eq__ comparing names and tracks.
You start from this, and edit it in the browser:
class Playlist:
def __init__(self, name, tracks):
self.name = name
self.tracks = tracks
def __str__(self):
pass
def __len__(self):
pass
def __eq__(self, other):
pass