SyntaxPilot
Courses/Python Coding Questions/Lesson 20
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Python Coding Questions · Lesson 20 of 30

OOP questions

__eq__ and __hash__ togethera Stack class with __len__ and __repr__class vs instance attribute trap

These are the notes for Python Coding Questions, episode 20: object-oriented programming (OOP) questions. Three classics: when are two objects equal, and why does a set suddenly call your class unhashable? A Stack class that works with print() and len() like a real Python object. And a list in a class body that every student ends up sharing.

Every program was run with Python 3.13 (python3 main.py), the SyntaxPilot compiler's Python command. Every output below is real (memory addresses change from run to run).

A quick reminder: a class is a blueprint; an object (or instance) is one thing built from it. An attribute is a value stored on an object or a class (book.isbn); a method is a function defined in a class (stack.push(x)). __init__ runs when a new object is made, and self is the object being worked on. Methods with two underscores on each side, such as __init__, are called dunder methods ("double underscore"); Python calls them for you at special moments.

Q1: __eq__ and __hash__

Real-life example: a library's return desk scans each returned book and makes a Book object with its ISBN (the book's unique number) and title. Today one book was scanned twice. The returned books are counted with a set, which should drop duplicates, but the system thinks two different books came back. For a library, the same ISBN means the same book.

Attempt 1: no __eq__

class Book:
    def __init__(self, isbn, title):
        self.isbn = isbn
        self.title = title

a = Book("978-0", "Python Basics")
b = Book("978-0", "Python Basics")    # the same book, scanned twice
print(a == b)
print(a is b)

Output:

False
False

Why: for your own class, Python doesn't know what "equal" means, so == falls back to is: "are these the very same object in memory?" They're two objects, so False. We define equality ourselves with __eq__.

Attempt 2: __eq__ only

__eq__(self, other) is called for self == other. If other isn't a Book, return NotImplemented (a special value meaning "I don't know how to compare with that"); Python then tries the other side and finally answers False.

class Book:
    def __init__(self, isbn, title):
        self.isbn = isbn
        self.title = title

    def __eq__(self, other):
        if not isinstance(other, Book):
            return NotImplemented
        return self.isbn == other.isbn

a = Book("978-0", "Python Basics")
b = Book("978-0", "Python Basics")
print(a == b)
print(a == "978-0")
returned = {a, b}
print(len(returned))

Output:

True
False
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    returned = {a, b}
               ^^^^^^
TypeError: unhashable type: 'Book'

Equality works, but now the set crashes. Before we wrote __eq__, a Book could go into a set; now it can't:

class Plain:
    pass

class WithEq:
    def __eq__(self, other):
        return True

print(Plain.__hash__)
print(WithEq.__hash__)

Output:

<slot wrapper '__hash__' of 'object' objects>
None

Defining __eq__ sets __hash__ to None, on purpose.

Why: how a set finds things

A hash is a number computed from an object (hash(x)). A set or dict uses it to pick a slot, and only then compares with == inside that slot. To check whether b is in the set, it goes to b's slot and looks only there. If a sits in a different slot, they're never even compared.

So the rule is: if a == b, then hash(a) == hash(b). The default hash is based on identity (two different objects get different hashes), which would break the rule as soon as you define your own ==. Python removes it until you write a matching one.

The fix: hash the same fields that __eq__ compares

class Book:
    def __init__(self, isbn, title):
        self.isbn = isbn
        self.title = title

    def __eq__(self, other):
        if not isinstance(other, Book):
            return NotImplemented
        return self.isbn == other.isbn

    def __hash__(self):
        return hash(self.isbn)      # the same field as __eq__

a = Book("978-0", "Python Basics")
b = Book("978-0", "Python Basics")
c = Book("978-1", "Clean Code")
returned = {a, b, c}
print(len(returned))
print(hash(a) == hash(b))
stock = {a: 3}
print(stock[b])

Output:

2
True
3

Two books in the set (the duplicate scan is gone), equal hashes, and b finds a's stock. Set and dict lookups stay O(1) on average, because the hash goes straight to the right slot. For several fields, hash a tuple of them: hash((self.isbn, self.edition)).

Never change a hashed field while the object is in a set or is a dict key: it would now sit in the wrong slot and can't be found.

class Book:
    def __init__(self, isbn):
        self.isbn = isbn
    def __eq__(self, other):
        return isinstance(other, Book) and self.isbn == other.isbn
    def __hash__(self):
        return hash(self.isbn)

a = Book("978-0")
shelf = {a}
a.isbn = "978-9"            # changed while inside the set
print(a in shelf)
print(Book("978-9") in shelf, Book("978-0") in shelf)

Output:

False
False False

The everyday answer: @dataclass(frozen=True)

A dataclass writes __init__, __repr__ and __eq__ from the fields you list. With frozen=True the fields can't be changed, and it also writes a matching __hash__.

from dataclasses import dataclass

@dataclass(frozen=True)
class Book:
    isbn: str
    title: str

a = Book("978-0", "Python Basics")
b = Book("978-0", "Python Basics")
print(a == b, len({a, b}))
print(a)
a.isbn = "978-9"

Output:

True 1
Book(isbn='978-0', title='Python Basics')
Traceback (most recent call last):
  File "main.py", line 12, in <module>
    a.isbn = "978-9"
    ^^^^^^
  File "<string>", line 16, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'isbn'

Note: a dataclass compares all fields (here ISBN and title). To compare by ISBN only, write __eq__ and __hash__ by hand, as above, or mark title with field(compare=False).

Q2: A Stack class

Real-life example: at a wedding buffet, washed plates go on top of the pile (push); a guest always takes the top plate (pop); sometimes you just look at the top plate (peek). The last plate put down is the first one taken: Last In, First Out, or LIFO. A stack is a collection with exactly these rules.

Attempt 1: a thin wrapper around a list

class Stack:
    def __init__(self):
        self.items = []
    def push(self, x):
        self.items.append(x)
    def pop(self):
        return self.items.pop()

plates = Stack()
plates.push("red")
plates.push("blue")
print(plates)
print(plates.pop(), plates.pop())
print(plates.pop())

Output:

<__main__.Stack object at 0x7f106a936f90>
blue red
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    print(plates.pop())
          ~~~~~~~~~~^^
  File "main.py", line 7, in pop
    return self.items.pop()
           ~~~~~~~~~~~~~~^^
IndexError: pop from empty list
class Stack:
    def __init__(self):
        self.items = []
    def push(self, x):
        self.items.append(x)

plates = Stack()
plates.push("red")
print(len(plates))

Output:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(len(plates))
          ~~~^^^^^^^^
TypeError: object of type 'Stack' has no len()

Three problems: print shows a memory address, the empty-pop error talks about a list (a hidden detail of our class), and len() doesn't work.

Why: dunder methods plug your class into Python

len(s) calls s.__len__(). print(s) calls s.__str__(), and if there isn't one, s.__repr__(). We wrote neither.

  • __repr__ should return an unambiguous text for developers, ideally looking like the code that builds the object: Stack(['red']). It's also what you see in the interactive shell and inside lists.
  • __str__ is an optional friendlier text for end users; without it, print uses __repr__.
  • With __len__, bool(s) and if s: work too: an empty stack is False.

The fix

A leading underscore (_items) is a convention meaning "internal: don't touch from outside".

class Stack:
    def __init__(self):
        self._items = []
    def push(self, x):
        self._items.append(x)
    def pop(self):
        if not self._items:
            raise IndexError("pop from empty stack")
        return self._items.pop()
    def peek(self):
        if not self._items:
            raise IndexError("peek at empty stack")
        return self._items[-1]
    def __len__(self):
        return len(self._items)
    def __repr__(self):
        return f"Stack({self._items})"

plates = Stack()
for p in ["red", "blue", "green"]:
    plates.push(p)
print(plates, len(plates))
print(plates.peek(), plates.pop(), plates)
print(bool(Stack()), bool(plates))
Stack().pop()

Output:

Stack(['red', 'blue', 'green']) 3
green green Stack(['red', 'blue'])
False True
Traceback (most recent call last):
  File "main.py", line 25, in <module>
    Stack().pop()
    ~~~~~~~~~~~^^
  File "main.py", line 8, in pop
    raise IndexError("pop from empty stack")
IndexError: pop from empty stack

push, pop, peek and len are all O(1): a Python list adds and removes at its end in constant (amortised) time. (Popping from the front, list.pop(0), is O(n), which is why a stack uses the end.)

__str__ and __repr__ side by side:

class Plate:
    def __init__(self, colour):
        self.colour = colour
    def __repr__(self):
        return f"Plate({self.colour!r})"
    def __str__(self):
        return f"a {self.colour} plate"

p = Plate("red")
print(p)
print(repr(p))
print([p, Plate("blue")])

Output:

a red plate
Plate('red')
[Plate('red'), Plate('blue')]

Q3: Class attributes vs instance attributes

Real-life example: a classroom has one whiteboard: everyone sees the same board. Each student also has their own notebook. A variable written in the class body is a whiteboard: one class attribute, shared by every object. A variable set with self.x = ... in __init__ is a notebook: one instance attribute per object.

Attempt 1: the list on the whiteboard

class Student:
    subjects = []                  # meant: each student's subjects

    def __init__(self, name):
        self.name = name

asha = Student("Asha")
ravi = Student("Ravi")
asha.subjects.append("Maths")
print(ravi.subjects)
print(asha.subjects is ravi.subjects)

Output:

['Maths']
True

Why: the class body runs once, when the class is created, so there's one list, stored on the class. asha.subjects finds no subjects of her own, so Python looks in the class and finds the shared one; append changes it for everyone. It's the same root cause as the mutable default argument in episode 18: one object made once and shared.

How attribute lookup works

Reading obj.x: Python looks in the object's own attributes (obj.__dict__) first, then in the class. Writing obj.x = ... always writes to the object itself, never to the class: it creates a new instance attribute that hides the class one. That's called shadowing.

The fix

class Student:
    school = "SyntaxPilot School"  # class attribute: shared

    def __init__(self, name):
        self.name = name
        self.subjects = []         # instance attribute: one each

asha = Student("Asha")
ravi = Student("Ravi")
asha.subjects.append("Maths")
print(asha.subjects, ravi.subjects)

asha.school = "City School"        # makes a NEW attribute on asha
print(asha.school, "|", ravi.school, "|", Student.school)
print(asha.__dict__)
Student.school = "Green Valley"
print(ravi.school, "|", asha.school)

Output:

['Maths'] []
City School | SyntaxPilot School | SyntaxPilot School
{'name': 'Asha', 'subjects': ['Maths'], 'school': 'City School'}
Green Valley | City School
  • __init__ runs for every new object, so each student gets a new list.
  • asha.school = ... didn't change the class; it gave Asha her own school, visible in asha.__dict__.
  • Changing Student.school changes it for everyone who doesn't have their own (Ravi), but not for Asha.
  • Class attributes are right for things that really are shared: constants, settings, a count of all objects (changed through the class name).
class Student:
    count = 0                       # how many students exist
    def __init__(self, name):
        self.name = name
        Student.count += 1          # through the CLASS, not self

Student("Asha"); Student("Ravi"); Student("Neha")
print(Student.count)

Output:

3

Common mistakes (and what you really see)

Mistake What you see Why Fix
no __eq__ a == b is False for equal data == falls back to is write __eq__
__eq__ without __hash__ TypeError: unhashable type: 'Book' __eq__ sets __hash__ to None hash the same fields
hashing a field __eq__ doesn't use (or vice versa) duplicates in sets, failed lookups equal objects with different hashes hash exactly the compared fields
changing a hashed field inside a set a in shelf is False the object is in the wrong slot make it immutable (frozen=True)
return False instead of NotImplemented for other types comparisons the other class could answer are cut short Python can't try the other side return NotImplemented
print(stack) with no __repr__ <__main__.Stack object at 0x...> the default repr def __repr__
len(stack) with no __len__ TypeError: object of type 'Stack' has no len() len() calls __len__ def __len__
pop on an empty list-based stack IndexError: pop from empty list the error leaks the list raise IndexError("pop from empty stack")
subjects = [] in the class body Ravi gets Asha's subject one list for the class self.subjects = [] in __init__
self.count += 1 for a shared counter each object counts only itself it writes a new instance attribute Student.count += 1
assigning to a frozen dataclass FrozenInstanceError: cannot assign to field 'isbn' frozen fields can't change make a new object (dataclasses.replace)

Your turn: a Money class (solution)

Question: write Money(rupees, paise) with == and hashing, a clear repr, and + that carries paise: Money(10, 70) + Money(5, 50) is Money(16, 20).

Idea: store everything as paise inside (one integer), so equality, hashing and adding are simple, and 100 paise and 1 rupee are automatically equal. __add__ is called for +.

class Money:
    def __init__(self, rupees=0, paise=0):
        self._paise = rupees * 100 + paise

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return self._paise == other._paise

    def __hash__(self):
        return hash(self._paise)

    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        total = self._paise + other._paise
        return Money(total // 100, total % 100)

    def __repr__(self):
        return f"Money({self._paise // 100}, {self._paise % 100})"

print(Money(10, 70) + Money(5, 50))
print(len({Money(1, 0), Money(1, 0)}))
print(Money(0, 150) == Money(1, 50))
print(Money(2) + 5)

Output:

Money(16, 20)
1
True
Traceback (most recent call last):
  File "main.py", line 25, in <module>
    print(Money(2) + 5)
          ~~~~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'Money' and 'int'

The last line returns NotImplemented from __add__, so Python reports a clear TypeError instead of guessing.

Mini project: a library's return desk

Combine the three ideas: a frozen Book (equal by ISBN), a Stack of returned books (the last one returned is shelved first), and a class attribute for the library's name.

from dataclasses import dataclass, field

@dataclass(frozen=True)
class Book:
    isbn: str
    title: str = field(compare=False)    # equal by ISBN only

class ReturnDesk:
    library = "SyntaxPilot Library"       # shared by every desk

    def __init__(self):
        self._pile = []                   # one pile per desk
        self._seen = set()

    def scan(self, book):
        if book in self._seen:
            return f"{book.title}: already scanned"
        self._seen.add(book)
        self._pile.append(book)
        return f"{book.title}: received"

    def shelve_next(self):
        return self._pile.pop().title if self._pile else None

    def __len__(self):
        return len(self._pile)

    def __repr__(self):
        return f"ReturnDesk({len(self)} books)"

desk = ReturnDesk()
for b in [Book("978-0", "Python Basics"), Book("978-1", "Clean Code"), Book("978-0", "Python Basics (copy scan)")]:
    print(desk.scan(b))
print(desk, ReturnDesk.library)
print("shelve:", desk.shelve_next(), "| left:", len(desk))

Output:

Python Basics: received
Clean Code: received
Python Basics (copy scan): already scanned
ReturnDesk(2 books) SyntaxPilot Library
shelve: Clean Code | left: 1

Practice questions (with solutions)

1. A Queue class (first in, first out) using collections.deque.

Solution

A queue is first in, first out, like a ticket line. A deque ("deck", double-ended queue) adds and removes at both ends in O(1); a list's pop(0) is O(n).

from collections import deque

class Queue:
    def __init__(self):
        self._items = deque()
    def enqueue(self, x):
        self._items.append(x)
    def dequeue(self):
        if not self._items:
            raise IndexError("dequeue from empty queue")
        return self._items.popleft()
    def __len__(self):
        return len(self._items)
    def __repr__(self):
        return f"Queue({list(self._items)})"

q = Queue()
for name in ["Asha", "Ravi", "Neha"]:
    q.enqueue(name)
print(q.dequeue(), q, len(q))

Output:

Asha Queue(['Ravi', 'Neha']) 2

2. A MinStack: push, pop, and get_min() all in O(1).

Solution

Keep a second stack holding the minimum so far at each level. Pop both together.

class MinStack:
    def __init__(self):
        self._items = []
        self._mins = []
    def push(self, x):
        self._items.append(x)
        self._mins.append(x if not self._mins else min(x, self._mins[-1]))
    def pop(self):
        self._mins.pop()
        return self._items.pop()
    def get_min(self):
        return self._mins[-1]

s = MinStack()
for x in [5, 3, 7, 2]:
    s.push(x)
print(s.get_min())
s.pop()
print(s.get_min())
s.pop(); s.pop()
print(s.get_min())

Output:

2
3
5

3. A Point(x, y) usable as a dict key, counting visits to grid cells.

Solution
from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

visits = {}
for p in [Point(0, 0), Point(1, 2), Point(0, 0)]:
    visits[p] = visits.get(p, 0) + 1
print(visits)

Output:

{Point(x=0, y=0): 2, Point(x=1, y=2): 1}

4. Use the stack: check if brackets are balanced.

Solution

Push every opening bracket; on a closing bracket, the top must be its partner. At the end the stack must be empty. O(n) time, O(n) space.

def balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack

print(balanced("print(a[0])"), balanced("(]"), balanced("(("))

Output:

True False False

Quick quiz

What does this print?

class Counter:
    total = 0
    def add(self):
        self.total += 1

a, b = Counter(), Counter()
a.add(); a.add(); b.add()
print(a.total, b.total, Counter.total)

(A) 3 3 3 (B) 2 1 0 (C) 2 1 3 (D) 0 0 0

Answer

(B). self.total += 1 reads total (found on the class: 0), adds 1, and writes the result onto the object. So a gets its own total of 2, b its own 1, and the class's total stays 0.

class Counter:
    total = 0
    def add(self):
        self.total += 1

a, b = Counter(), Counter()
a.add(); a.add(); b.add()
print(a.total, b.total, Counter.total)

Output:

2 1 0

Interview questions

  1. What does == do for a class without __eq__? It compares identity, like is.
  2. Why does defining __eq__ make objects unhashable? Python sets __hash__ to None, because the default identity-based hash would break the rule "equal objects have equal hashes".
  3. How do you write __hash__? Hash the same fields __eq__ compares, usually as a tuple: hash((self.a, self.b)). Those fields should never change while the object is used as a key.
  4. What does NotImplemented do in __eq__? It tells Python this method can't compare with that type, so Python tries the other operand's method and finally falls back to identity (False).
  5. __repr__ vs __str__? __repr__ is the unambiguous developer text (used in the shell, in containers, and by print when there's no __str__); __str__ is the friendly user text.
  6. What does @dataclass(frozen=True) give you? __init__, __repr__, __eq__, a matching __hash__, and fields that can't be reassigned.
  7. Implement a stack. What are the complexities? A list with append / pop() / [-1]: all O(1). Raise a stack-specific error on empty pop/peek, and add __len__ and __repr__.
  8. Class attribute vs instance attribute? A class attribute is defined in the class body and shared by all instances; an instance attribute is set on self and belongs to one object.
  9. What happens on obj.attr = value when attr is a class attribute? A new instance attribute is created on obj, shadowing the class attribute for that object only.
  10. Why is items = [] in a class body a bug? The class body runs once, so all instances share one list. Create it in __init__.

Glossary

Term Meaning Example
Class / object (instance) A blueprint / one thing built from it Book / Book("978-0", ...)
Attribute A value stored on an object or class book.isbn
Method A function defined in a class stack.push(x)
self The object a method is working on self.isbn
Dunder method A __name__ method Python calls for you __init__, __len__
Identity Being the very same object in memory a is b
__eq__ Called for == def __eq__(self, other)
NotImplemented "I can't compare with that type" return NotImplemented
isinstance Checks an object's type isinstance(other, Book)
Hash A number computed from an object, used to pick a slot hash("978-0")
Hashable Has a fixed hash; can be a set item or dict key str, tuple, frozen dataclass
__hash__ Called by hash(), sets and dicts return hash(self.isbn)
Slot (bucket) The place a set/dict stores an item, chosen by its hash
Dataclass A class whose __init__, __repr__, __eq__ are written from its fields @dataclass
frozen=True Fields can't be reassigned; adds __hash__ @dataclass(frozen=True)
FrozenInstanceError Raised when assigning to a frozen field a.isbn = ...
Stack Last in, first out collection a pile of plates
LIFO Last In, First Out push, then pop
push / pop / peek Add on top / take the top / look at the top append / pop() / [-1]
__len__ Called by len() and bool() return len(self._items)
__repr__ The developer text of an object Stack(['red'])
__str__ The user-friendly text used by print a red plate
_name Convention for "internal" self._items
Amortised O(1) Constant on average over many operations list.append
Queue / FIFO First in, first out collection a ticket line, deque
Class attribute Defined in the class body, shared school = "..."
Instance attribute Set on self, one per object self.subjects = []
__dict__ An object's own attributes asha.__dict__
Shadowing An instance attribute hiding a class attribute of the same name asha.school = "City School"
__add__ Called for + Money(1) + Money(2)

Summary

  • Without __eq__, == means "the same object". Define __eq__ on the fields that decide equality, returning NotImplemented for other types.
  • Defining __eq__ removes __hash__. Write __hash__ from the same fields; equal objects must have equal hashes. Don't change those fields while the object is a key. @dataclass(frozen=True) does all of it.
  • Dunder methods plug your class into Python: __len__ for len() and bool(), __repr__ (and __str__) for print(). A stack on a list gives O(1) push, pop and peek; raise stack-specific errors.
  • The class body runs once: a list there is shared by every object. Put per-object state in __init__. Assigning obj.x creates an instance attribute that shadows the class one.
  • Next episode: recursion questions: power and sum of digits, all permutations of a string, all subsets, and RecursionError.