Module lessons (3/4)
Special methods (dunder)
__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__usingisinstanceandNotImplemented. - 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
- 11.
__str__vs__repr__: end user and developer - 22.
__eq__to compare values instead of memory addresses - 33.
__len__and automatic truthiness - 44. Immutable algebraic operators with
__add__ - 5Check for understanding
- 6Test yourself
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.