Dunder methods and abstract classes
Equality, ordering and hashing that agree, NotImplemented, and interfaces with abc.
Foundations · Python for data engineers · Gold · Objects that behave like values, lesson 1 of 1
On this page
Read first: Classes, properties and dataclasses (skip if you know it)
In plain words first
When you write a == b or print(a), Python does not know what your class means by "equal" or how it should look. It looks for a methodmethod: A function defined inside a class and called on an object, like name.upper() or order.total(). Learn more → with a special name and calls it for you. Those names start and end with two underscores, so people call them dunder methods ("double underscore").
You write
print(p), p == q, p < q, {p, q}Python calls
p.__repr__(), p.__eq__(q), p.__lt__(q), p.__hash__()Here is a class with none of them. Two prices of ₹5 are not equal, because by default == asks "is this the very same object?", and printing shows a memory address:
class Plain:
def __init__(self, rupees):
self.rupees = rupees
a, b = Plain(5), Plain(5)
print("a == b:", a == b)
print("looks like:", str(a).split(" at ")[0] + ">")
Output from a real run
a == b: False looks like: <__main__.Plain object>
Add two methods and the class behaves the way you expect. __repr__ returns the text to show; __eq__ answers "are these equal?":
class Price:
def __init__(self, rupees):
self.rupees = rupees
def __repr__(self):
return f"Price({self.rupees})"
def __eq__(self, other):
if not isinstance(other, Price):
return NotImplemented # "I cannot compare with that"
return self.rupees == other.rupees
print(Price(5))
print("equal:", Price(5) == Price(5))
print([Price(1), Price(2)])
try:
{Price(5)}
except TypeError:
print("in a set: TypeError, Price is unhashable")
Output from a real run
Price(5) equal: True [Price(1), Price(2)] in a set: TypeError, Price is unhashable
The last line is a surprise: once you define __eq__, the objects can no longer go in a set or be dict keys. The rest of this lesson explains why, and how to fix it properly.
Unlock the full lesson
You have read the free part. The rest of this advanced lesson:
- Operators are method calls
- A value type done right
- The hash rule
- NotImplemented
- Abstract base classes
- When to reach for this
- Common mistakes
- Key takeaways
- Interview prep with 3 follow-up questions
- Check yourself: 4 questions
Unlock it with the Complete pass (every advanced problem and lesson) or on its own.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Algorithms interviewers ask · 7 min readHeaps, top-k and k-way merges
heapq, top-k in O(n log k), tie-breaking tuples, and merging sorted streams.
Related lessons
Classes, properties and dataclassesPython for data engineers · 8 min read
Iterators, yield from and itertools
Previous: Wrangling data without pandas
Primary sources: Data model · abc