Skip to main content
Module 7 · Lesson 3 of 427/36 in the course~16 min
Module lessons (3/4)

Special methods (dunder)

Lesson preview5 hands-on exercises readyPython Course · Module 7 — Classes and modules

__str__, __repr__, __eq__, __len__: integrating custom objects with Python operators and built-ins.

What you'll learn in this lesson

  • Understanding the Python Data Model: How built-in operators and functions (str, len, ==, +) invoke dunder methods.
  • Distinguish the role of __str__ (user readability) versus __repr__ (unambiguous inspection for debugging).
  • Correctly implement __eq__ using isinstance and NotImplemented.
  • Make your classes compatible with collections, iterations, and mathematical operators (__len__, __add__, __lt__).

Overview

Special methods whose name begins and ends with a double underscore (dunder, from double underscore) form the Python Data Model. They are not meant to be called directly like obj.__len__(), but function as hooks that the language activates behind the scenes when you use idiomatic syntax.

When you write len(cart) or a == b or print(money), the interpreter translates the operation into the corresponding special method call, turning your custom classes into first-class citizens of the language.

Sections covered in this lesson

  1. 11. __str__ vs __repr__: end user and developer
  2. 22. __eq__ to compare values instead of memory addresses
  3. 33. __len__ and automatic truthiness
  4. 44. Immutable algebraic operators with __add__
  5. 5Check for understanding
  6. 6Test yourself
Pro Lesson · Module 7 — Classes and modules

Unlock "Special methods (dunder)" and the full Python Course curriculum

__str__, __repr__, __eq__, __len__: integrating custom objects with Python operators and built-ins.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Python Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.