Dunder methods

Classes & Objects, lesson 5 of 6

🏗️ Classes & Objects, lesson 5 of 6

Dunder methods

Make your objects print nicely, compare, sort and work with len() and +.

11 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Printing a plain object shows something like <__main__.Point object at 0x10a3...>. Not helpful! Python's built-in syntax calls special dunder (double underscore) methods behind the scenes:

  • print(x), str(x) → x.__str__()
  • repr(x), items in a list → x.__repr__()
  • len(x) → x.__len__()
  • a == b → a.__eq__(b), a < b → a.__lt__(b)
  • a + b → a.__add__(b)

Define them, and your objects work like built-ins.

Example

__str__ and __repr__

__str__ is the friendly version for users; __repr__ is the precise one for developers (used in lists and debugging). Delete both methods to see the default.

Quiz

What does this print?

Equality and ordering. By default == only checks whether two names point at the very same object. Define __eq__ to compare by value. Define __lt__ and sorted(), min() and max() just work.

Example

Sortable playing cards

Delete __eq__ and the last line prints False: two separate objects are never equal by default.

Example

__len__, __contains__ and __add__

With __len__, if playlist: is False for an empty playlist, just like an empty list.

Quiz

Which method does len(box) call?

Exercise

A 2D vector

Add four dunder methods to Vector:

  • __repr__ returns text like Vector(1, 2)
  • __eq__: equal when both x and y match
  • __add__ returns a new Vector with the parts added
  • __mul__ returns a new Vector scaled by a number: Vector(1, 2) * 3 is Vector(3, 6)