OOP Interview Drill and Checkpoint
60 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Treat this page as a mock round. Predict each output before running it, fix the bug, then explain your answer out loud in two or three sentences.
Predict the output
Trace the code line by line. Ask where each name lives: instance, class, or a parent class. Then follow super() along the MRO.
class Base: log = []
def run(self): self.log.append("base")
class Child(Base): def run(self): super().run() self.log.append("child")
Child().run()Base().run()print(Base.log)Example 1 · Tracing attributes, properties and shadowing
class Account: bank = "MentorBank"
def __init__(self, owner, balance): self.owner = owner self._balance = balance
@property def balance(self): return self._balance
a = Account("Asha", 500)b = Account("Ravi", 200)a.bank = "OtherBank"print(a.bank, b.bank, Account.bank)print(a.balance + b.balance)print(sorted(vars(a)))OtherBank MentorBank MentorBank 700 ['_balance', 'bank', 'owner']
What this code does
- Assigning
a.bankcreated an instance attribute, so onlyachanged. balanceis a property and is not invars(a); the stored value_balanceis.
log is one list on Base, shared by every class below it. Nothing creates a new one, so each append adds to the same list.
Spot the bug
Most bug questions in OOP rounds use a shared default. The default is built once, when the function or class body runs.
class Basket: def __init__(self, items=[]): self.items = items
def add(self, item): self.items.append(item)
a = Basket()b = Basket()a.add("pen")print(b.items)Example 2 · The fixed basket, with a safe equality
class Basket: def __init__(self, items=None): self.items = [] if items is None else list(items)
def add(self, item): self.items.append(item)
def __eq__(self, other): return isinstance(other, Basket) and self.items == other.items
__hash__ = None
a = Basket()b = Basket()a.add("pen")print(a.items, b.items)print(a == b, a == Basket(["pen"]))['pen'] [] False True
What this code does
- Each basket now gets its own list.
- A mutable object with value equality sets
__hash__ = Noneon purpose, so it cannot sit in a set by mistake.
Both baskets use the one default list. Use items=None and write self.items = [] if items is None else items.
Pick the design
Say the relationship as a sentence. "A Stack is a list" fails, because a stack must not allow inserting in the middle. "A Stack has a list" fits.
class Stack: def __init__(self): self._items = []
def push(self, item): self._items.append(item)
def pop(self): return self._items.pop()
def __len__(self): return len(self._items)Example 3 · A small design: payments with parts
from abc import ABC, abstractmethodfrom dataclasses import dataclass
class Payment(ABC): @abstractmethod def pay(self, amount): ...
class CardPayment(Payment): def pay(self, amount): return f"card paid {amount}"
class UpiPayment(Payment): def pay(self, amount): return f"upi paid {amount}"
@dataclassclass Checkout: method: Payment
def complete(self, amount): return self.method.pay(amount)
for m in (CardPayment(), UpiPayment()): print(Checkout(m).complete(250))card paid 250 upi paid 250
What this code does
Checkouthas a payment method and never inherits from one.- Adding a wallet payment means one new class and no change to
Checkout.
The caller sees only push, pop and len. The list is a private detail that can change later.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Write Order with a class attribute count that grows with each new order. Create three orders and print Order.count.
3
Exercise 2· Easy
Write Person(name) and Student(Person) with marks. Student.describe() must reuse the parent's describe() and return <name> scoring <marks>. Print it for Asha and 82.
Asha scoring 82
Exercise 3· Easy
Write Customer(first, last) with a read-only property full_name returning <first> <last>. Print it for Asha Rao.
Asha Rao
Exercise 4· Medium
Write add_item(item, items=None) that returns the list with the item added, using the safe default. Call it with a and then with b and print both results on separate lines.
['a'] ['b']
Exercise 5· Medium
Write a dataclass Team with name and a members list that defaults to a new empty list. Create two teams, add Asha to the first and print both teams' members, one per line.
['Asha'] []
Exercise 6· Medium
Write an abstract Notifier with send(text), then Email and Sms implementations returning email: <text> and sms: <text>. Write broadcast(notifiers, text) that prints each result. Call it with both for Order shipped.
email: Order shipped sms: Order shipped
Exercise 7· Hard
Write Temp(c) with a property f for Fahrenheit that has a getter and a setter. Setting f = 212 must change c. Print c after setting 212, then set c = 0 and print f.
100.0 32.0
Exercise 8· Hard
Write Money(amount) with __add__, __eq__, __hash__, __lt__ and __repr__. Print sum([Money(5), Money(7)], Money(0)), then the sorted list [Money(9), Money(2), Money(5)], then the size of a set of Money(3) made twice.
Money(12) [Money(2), Money(5), Money(9)] 1
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of OOP Questions
Python Programming has 21 sections, 110 modules and 609 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: Lists, Tuples and Slicing