Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Advanced Python & Software Engineering — Alpha School

Lesson 3: Special Methods and the Python Data Model

You have already met one special method: __init__. Python has many more, and they are the secret behind why built-in operations work on your own objects. When you write len(my_list), Python is really calling my_list.__len__(). When you write str(obj), it calls obj.__str__(). These double-underscore methods — often called dunder methods — are hooks into the language itself. Define them on your class, and your objects start behaving like native Python values.

The most useful dunders to learn first are __str__ for a readable description, __repr__ for an unambiguous one (ideally something you could paste back into code), __eq__ for equality, and __len__ for length. The example below is a small Playlist class: len() counts its songs, == compares two playlists by their songs, and printing a playlist shows something helpful instead of the default <__main__.Playlist object at 0x...>, which tells you nothing at all.

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

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

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

    def __repr__(self):
        return f"Playlist({self.name!r}, {self.songs!r})"

    def __eq__(self, other):
        if not isinstance(other, Playlist):
            return NotImplemented
        return self.name == other.name and self.songs == other.songs


road = Playlist("Road Trip", ["Song A", "Song B"])
print(road)        # Road Trip: 2 songs
print(len(road))   # 2
print(road == Playlist("Road Trip", ["Song A", "Song B"]))  # True

The data model is a contract

Python's data model is a set of these hooks, and learning it is what turns a Python user into a Python programmer. Arithmetic operators have hooks too: __add__ for +, __lt__ for <, and so on. You can even make your objects work with for loops by defining __iter__ — the next unit explores that in depth. The key idea is restraint: only implement the dunders that make sense for your class. A playlist has a natural length, so __len__ is a good fit; adding two playlists together would be surprising, so leave __add__ alone.

One detail worth noticing is the NotImplemented return in __eq__. When you compare a playlist with something that is not a playlist, returning NotImplemented tells Python to try the other object's comparison instead, and if that fails too, the answer is simply False. Returning it is more polite than raising an error, and it keeps == working smoothly with mixed types. Small choices like this are what make a class feel like it belongs in Python rather than fighting against it.

Going further

There is a subtle relationship between __str__ and __repr__ that is worth knowing. When you print a list of playlists, Python shows the __repr__ of each item, not the __str__ — because a list is a container, and containers show the developer-facing form. So if you only define __str__, your objects will still look cryptic inside lists and dictionaries. The practical rule is to always define __repr__, and to add __str__ only when you want a prettier form for end users. If you define just one, make it __repr__.

One more dunder deserves a warning. If you define __eq__ on a class, Python automatically sets __hash__ to None, which means instances of your class can no longer be used as dictionary keys or put in sets. The reasoning is sound: objects that compare equal should hash equally, and Python cannot guess the right hash for your equality rule. If you need your objects to be hashable, define __hash__ yourself, making sure that objects that compare equal produce the same hash. For a playlist, hashing the tuple of the name and songs would be a natural choice.

As a practical exercise, add __len__ and __getitem__ to the Playlist class from this lesson, so that len(playlist) counts the songs and playlist[0] returns the first one. Two dunders are enough to make your object work with for loops, with list(), and with the in operator, because Python's sequence protocol is built on exactly those two hooks. That is the data model at its most rewarding: a small amount of work unlocks a large amount of built-in behaviour, and your class starts to feel like a native Python type rather than a visitor from another language.

Key Terms

Dunder method
A special method whose name starts and ends with double underscores, such as __init__ or __len__.
Data model
Python's set of special-method hooks that let your classes work with built-in operations like len(), == and print().
__str__
Returns a readable, user-friendly string for an object, used by print() and str().
__repr__
Returns an unambiguous string for an object, used in the interactive prompt and ideally valid Python code.
__eq__
Defines what == means for a class; should return NotImplemented for types it cannot compare with.
__len__
Defines what len() returns for an object.
NotImplemented
A special value a comparison method returns to say it cannot handle the other type, letting Python try the other side.

Discussion Questions

  1. Why should __repr__ ideally show something you could paste back into code, while __str__ just needs to be readable?
  2. Which dunder methods would a Fraction class need, and which would be silly to add? Why?
  3. What would happen if __eq__ raised an error instead of returning NotImplemented when comparing a Playlist with a number?

Practice Questions

  1. What does print(road) show, and which method produces it?
  2. Why does the example define both __str__ and __repr__?
  3. What does len(road) return, and how?
  4. Two playlists have the same songs but different names. Are they equal under this __eq__?
  5. Name the dunder method that would let you write playlist1 + playlist2.
Show answers
  1. "Road Trip: 2 songs", from __str__. print() calls str() on the object, which uses __str__.
  2. They serve different audiences: __str__ is for users, __repr__ is for developers debugging. The interactive prompt uses __repr__, while print() uses __str__.
  3. 2. len() calls the class's __len__ method, which returns the length of the songs list.
  4. No. __eq__ compares both name and songs, so a different name makes them unequal.
  5. __add__. Python calls __add__ for the + operator; the lesson advises only adding it when the result would feel natural.
Keep reading to complete this lesson