1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

Magic methods

Methods with double underscores (dunders) hook into Python's built-in behaviour:

  • __str__ controls what print(obj) and str(obj) show
  • __len__ makes len(obj) work
  • __eq__ defines ==

Define these methods with self, just like other methods: def __str__(self): returns text, and def __len__(self): returns a nonnegative integer.

For equality, Python passes the other value as a second argument:

def __eq__(self, other):
    if not isinstance(other, type(self)):
        return NotImplemented
    return self.value == other.value

isinstance(other, SomeClass) checks whether other belongs to that class (or a subclass). NotImplemented is a special return value, not an exception: it lets Python try the other object's comparison before falling back. Check the type before reading its attributes.

Without __str__ you get something ugly like <__main__.Book object at 0x...>.

See it run

class Money:
    def __init__(self, cents):
        self.cents = cents

    def __add__(self, other):
        return Money(self.cents + other.cents)

    def __str__(self):
        return f"{self.cents / 100:.2f}"

a = Money(250)
b = Money(175)
total = a + b
print(total)

Magic methods let Python syntax like + and print call your code.

Practice magic methods

Exercise 1

Give Book in the code editor below a __str__ that returns TITLE by AUTHOR using each book's attributes (e.g. "Dune by Frank Herbert"), and a __len__ that returns its page count.

Exercise 2

Build Playlist(name, songs) storing a list copy. len(playlist) gives the current song count and str(playlist) returns NAME (N tracks). Both must reflect later edits to playlist.songs, including empty playlists.

Exercise 3

Build Coordinate(x, y). str(point) is (x, y). Two Coordinates compare equal only when both axes match. For unrelated types, __eq__ returns NotImplemented so comparisons stay safe.

The explanation and tasks are public. Running this lesson requires an account with course access.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest