Skip to content

Magic (Dunder) Methods

Beginning of the lesson

Magic (Dunder) Methods

Hook your own classes into Python's built-in syntax

Big Idea: A magic method (or dunder method, short for "double underscore") is a specially named method like __str__ or __eq__ that Python calls for you when you use ordinary syntax such as print(obj), a == b, len(obj), or a + b. You rarely call them by name; you define them so your objects behave like built-in types.
By the end of this topic you will be able to:
  • explain what dunder methods are and when Python invokes them,
  • give objects a readable form with __repr__ and __str__,
  • define value equality with __eq__,
  • make len() and truthiness work through __len__,
  • overload operators such as + and * with __add__ and __mul__,
  • reason about the trade-offs, including NotImplemented and equality/hashing.

1. What is a dunder method?

Every time you write a + b, len(x), or print(obj), Python quietly translates that syntax into a method call on the object. Those methods have names wrapped in double underscores — __add__, __len__, __str__ — which is why Python programmers pronounce them "dunder" (double-under). They are also called special methods.

Analogy: think of dunder methods as electrical sockets in a wall. The wall (Python) already knows how to send power through a standard socket. When your class provides the matching socket — the right method name and shape — the built-in machinery plugs straight in. You do not rewire the house; you just fit the standard plug so len(), ==, and print() know what to do with your object.

The key mental model: you almost never call dunder methods directly. You write the natural syntax, and Python dispatches to the dunder for you. Writing obj.__len__() works, but the whole point is that you can just write len(obj).

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers