Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

4.4 Special Methods

How it works

Defining the string representation and equality methods makes an object print usefully and compare sensibly.

Implement a readable representation for any class you will debug.

Common error

Comparing two objects without defining equality, which compares identity and returns false for equal values.

Worked example

Python

class Playlist:
    def __init__(self, songs):
        self.songs = list(songs)
    def __len__(self):
        return len(self.songs)
    def __str__(self):
        return f"Playlist({len(self)} songs)"

p = Playlist(["A", "B"])
print(len(p))
print(p)

Output

2
Playlist(2 songs)

Special methods let ordinary language operations work with a class. len calls the length protocol, while str and print use a suitable text representation.

Exercises

4.4.1 · Explain

What return type should __len__ produce, and what should __str__ return?

Show solution

__len__ must supply an appropriate nonnegative integer length. __str__ returns a string representation, not a printed side effect.

4.4.2 · Write code

Create a Label class whose string representation is its stored text, then print Label("ready").

Show solution

Return the text from __str__.

One valid solution

class Label:
    def __init__(self, text):
        self.text = text
    def __str__(self):
        return self.text

print(Label("ready"))

Expected output

ready
Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic