Printing and comparing objects
Last updated
Print a book and Python shows something like <__main__.Book object at 0x10a3f>. Make two books with the same title and author, and Python says they aren't equal. In this lesson you'll fix both, with methods Python calls for you: __str__ and __repr__ for printing, __eq__ for ==, __lt__ for sorting, and __hash__ so books can go in a set or be dict keys.
By the end of this lesson you can
- Write
__str__and__repr__, and say which oneprint, f-strings and lists use - Write
__eq__so objects with the same data are equal - Write
__lt__sosorted,minandmaxwork on your objects - Write
__hash__to match__eq__, and read the error when it's missing
A book that prints badly, and two equal books that aren't
Here's a Book with nothing but __init__. The program prints one book, then asks whether two books with the same title and author are equal. Run it.
The second line says False. Unless the class says otherwise, == on objects asks the same question as is: are they the very same object? a and b are two objects, so they aren't equal, even though they hold the same data.
Both are fixed with methods that have two underscores on each side, like __init__. They're called special methods or dunder methods ("double underscore"). You write them, and Python calls them for you when you print, compare or sort.
__str__ and __repr__
There are two ways to turn an object into text, for two different readers.
__str__ is for people using the program. print and f-strings call it. Make it read well: Dune by Frank Herbert.
__repr__ is for programmers. It's what repr() shows, and what you see when a book is inside a list or dict. Make it look like the code that would make the object again: Book('Dune', 'Frank Herbert'). The !r inside the braces puts each value's own repr there, with its quotes.
Line 17 prints a list, and a list shows its items with __repr__, so you can tell text from numbers. Delete the __str__ method and run it again: print falls back to __repr__. If you write only one, write __repr__.
| When you write | Python calls | Made for |
|---|---|---|
print(book), str(book), f"{book}" | __str__ | People using the program |
repr(book), a list or dict of books, Watch it run | __repr__ | Programmers reading output |
Either, when the class has only __repr__ | __repr__ | __str__ falls back to it |
Watch it run: from now on the values table shows each book with your __repr__.
__eq__
a == b calls a.__eq__(b). Write it to say when two books count as the same. Here it's when the title and author both match. Putting each book's two values in a tuple compares them both in one go.
a == bis nowTrue, thougha is bis stillFalse. They're equal, but they're two objects.!=(line 17) works too: Python flips the answer from__eq__.inand.index()look for an equal item, so line 19 findsain a shelf that holds onlyb.
What should count as equal is your choice. Two copies of the same edition are the same book to a catalogue, but not to a shelf counting copies. Stage 4 adds a check for comparing a book with something that isn't a book.
__lt__ and sorting
sorted(), min() and max() need to know which of two books comes first. They ask with <, which calls __lt__ ("less than"). This one orders books by author, then by title, again by comparing tuples.
Emma and Persuasion have the same author, so the titles decide. Python only needs __lt__ to sort. It never uses > for it.
Now delete the __lt__ method and run it again. Python stops with a TypeError: '<' not supported between instances of 'Book' and 'Book'. Without __lt__, Python has no idea what order books go in.
If you only need one order once, you don't need __lt__ at all: sorted(shelf, key=lambda b: b.title) from lesson 2.5 works on any object. Write __lt__ when the class has one natural order that everyone expects.
__hash__
Sets and dict keys find things fast using a hash: a number worked out from the value. Equal values must always give the same hash, or a set could hold two "equal" books, and a dict couldn't find a key that's equal to the one you stored.
That's why Python takes the hash away from a class that defines __eq__. Its old hash came from the object's identity, which would break the rule. If you want books in a set or as dict keys, write __hash__ yourself, hashing the same values __eq__ compares:
Line 21 removes the duplicate Dune: two books are left. Line 23 finds the copies with a new Book that's equal to the key.
Delete the __hash__ method and run it again. Python stops on line 21 with TypeError: unhashable type: 'Book'.
One more rule: once a book is in a set or is a dict key, don't change its title or author, or its hash would change and the set would lose it. Lesson 4.4 makes objects that can't change, which solves it for good.
In other languages
This step is optional. It's for anyone who will meet Java or Rust later.
| Python | Java | Rust | |
|---|---|---|---|
| As text, for people | __str__ | toString() | impl Display |
| As text, for programmers | __repr__ | toString() again: there’s only one | #[derive(Debug)], printed with {:?} |
| Equal | __eq__, used by == | equals(). == still means "same object" | PartialEq, used by == |
| In order | __lt__, used by < and sorted | compareTo() from Comparable | PartialOrd and Ord |
| Hash | __hash__. Equal objects need equal hashes | hashCode(), with the same rule | Hash, with the same rule |
The rule "equal objects need equal hashes" is the same in all three. Simple Rust 4.4 has Rust write most of these for you with #[derive]. Python can do that too, with dataclasses: that's the next lesson.
Check what you learned
Three questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Language Reference: Basic customization: __repr__, __str__, the comparison methods and __hash__
- The Python Language Reference: object.__repr__
- The Python Language Reference: object.__lt__: the rich comparison methods
- The Python Language Reference: object.__hash__: objects that compare equal must have the same hash
- Sorting Techniques: sorting uses only <
- Glossary: hashable
- Java API: Object: toString, equals and hashCode, which every Java class can override
- Java API: Comparable: how Java puts objects in order
- The Rust Programming Language: Derivable Traits: Display, Debug, PartialEq, PartialOrd and Hash in Rust