Chapter 10

Classes & OOP

Class vs instance attributes. Mutable class attribute trap. MRO. staticmethod vs classmethod. Dunder methods. Python OOP is full of subtle traps.

Questions: 18
Difficulty: ★★★★☆
The class attribute trap: Class attributes are shared across ALL instances. If the value is mutable (like a list), ALL instances see mutations. This is the OOP equivalent of the mutable default argument trap.
Class vs Instance Attributes
Q 01Predict the Output
class Counter:
    count = 0   # class attribute

    def __init__(self):
        Counter.count += 1

Counter()
Counter()
Counter()
print(Counter.count)
Output
3
Why? count is a class attribute — shared among all instances. Each time an instance is created, Counter.count += 1 increments the shared counter. This is the classic pattern for counting instances. Accessing through the class name (Counter.count) makes the intent clear.
Q 02Predict the Output
class Dog:
    tricks = []   # mutable class attribute — danger!

    def add_trick(self, trick):
        self.tricks.append(trick)

fido = Dog()
rex = Dog()
fido.add_trick("sit")
rex.add_trick("shake")
print(fido.tricks)
Output
['sit', 'shake']
Why? tricks is a class attribute — one list shared by ALL Dog instances. Both fido and rex append to the same list. Fix: move the list to __init__: self.tricks = []. This creates a separate list per instance.
Q 03Predict the Output
class A:
    x = 10

a = A()
print(a.x)     # reads class attribute
a.x = 20       # creates instance attribute
print(a.x)     # reads instance attribute
print(A.x)     # class attribute unchanged
Output
10 20 10
Why? Instance attribute lookup: Python first checks the instance's __dict__, then the class. a.x = 20 creates an instance attribute that shadows the class attribute. The class attribute A.x is untouched. The instance now has its own x.
__init__ and __str__
Q 04Predict the Output
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Point({self.x}, {self.y})"

    def __repr__(self):
        return f"Point({self.x!r}, {self.y!r})"

p = Point(1, 2)
print(p)
print(repr(p))
Output
Point(1, 2) Point(1, 2)
Why? __str__ is called by print() and str() — human-readable output. __repr__ is called by repr() — developer-friendly, ideally valid Python to recreate the object. If __str__ is missing, Python falls back to __repr__.
Inheritance & MRO
Q 05Predict the Output
class Animal:
    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "Woof"

class Puppy(Dog):
    pass

p = Puppy()
print(p.speak())
print(isinstance(p, Animal))
Output
Woof True
Why? Method resolution follows MRO (Method Resolution Order): Puppy → Dog → Animal. Puppy doesn't define speak, so Python looks up to Dog which does. isinstance(p, Animal) is True because inheritance means Puppy IS-A Dog IS-A Animal.
Q 06Multiple Choice
class A:
    def hello(self): return "A"

class B(A):
    def hello(self): return "B"

class C(A):
    def hello(self): return "C"

class D(B, C):
    pass

print(D().hello())
Answer: b) "B".

Python uses C3 linearization for MRO. D.__mro__ is (D, B, C, A, object). Python searches left to right: D has no hello, B has it → "B" is returned. Python handles diamond inheritance correctly — no ambiguity errors, just a defined order.
Q 07Predict the Output
class Base:
    def __init__(self):
        print("Base init")

class Child(Base):
    def __init__(self):
        super().__init__()
        print("Child init")

Child()
Output
Base init Child init
Why? super().__init__() calls the parent class's __init__ first. Without the super() call, Base.__init__ would never run. Order: Base initializes first (because super() is called first in Child's init), then Child continues. This is the correct pattern for cooperative inheritance.
staticmethod vs classmethod
Q 08Predict the Output
class MyClass:
    value = 42

    @classmethod
    def class_method(cls):
        return cls.value

    @staticmethod
    def static_method():
        return "no class or self"

print(MyClass.class_method())
print(MyClass.static_method())
Output
42 no class or self
Why? @classmethod: receives the class (cls) as the first argument — not an instance. Used for factory methods and class-level operations. @staticmethod: receives neither class nor instance — it's a plain function attached to the class namespace. Can be called on class or instance.
Q 09Multiple Choice
class Circle:
    def __init__(self, radius):
        self.radius = radius

    @classmethod
    def from_diameter(cls, diameter):
        return cls(diameter / 2)

c = Circle.from_diameter(10)
print(c.radius)
Answer: a) 5.0.

This is the "alternative constructor" pattern — the most common use case for @classmethod. cls(diameter/2) calls Circle(5.0), creating and returning a new instance. The cls parameter (not Circle) allows this to work correctly in subclasses too.
Dunder Methods
Q 10Predict the Output
class Box:
    def __init__(self, items):
        self.items = items

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

    def __contains__(self, item):
        return item in self.items

b = Box([1, 2, 3])
print(len(b))
print(2 in b)
print(bool(b))
Output
3 True True
Why? Dunder methods customize how objects behave with built-in operations. __len__ makes len(b) work. __contains__ makes in work. bool(b) calls __bool__ if defined; if not, falls back to __len__ — since len > 0, bool is True.
Q 11Predict the Output
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)
Output
(4, 6)
Why? __add__ defines what + does for your class. v1 + v2 calls v1.__add__(v2), which returns a new Vector(4, 6). print() calls __str__ on that. Operator overloading lets your objects behave like built-in types.
Property
Q 12Predict the Output
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32

t = Temperature(100)
print(t.fahrenheit)
print(type(Temperature.fahrenheit))
Output
212.0 <class 'property'>
Why? @property turns a method into a getter that looks like an attribute — accessed as t.fahrenheit (no parentheses). On the class itself, Temperature.fahrenheit is the property descriptor object. Properties allow computed attributes with validation.
__eq__ and __hash__
Q 13Multiple Choice
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(1, 2)
d = {p1: "value"}
Answer: b) TypeError.

When you define __eq__, Python automatically sets __hash__ to None, making the class unhashable. If you want objects to be both equatable and usable as dict keys, you must explicitly define __hash__: def __hash__(self): return hash((self.x, self.y)).
Q 14Predict the Output
class A:
    pass

a1 = A()
a2 = A()
print(a1 == a2)
print(a1 is a2)
Output
False False
Why? Without a custom __eq__, Python's default equality check for objects is identity — same as is. Two different instances of A are never equal by default, even if they have the same (empty) state. This differs from value types like int/str where equality is by value.
dataclass
Q 15Predict the Output
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1)
print(p1 == p2)
Output
Point(x=1, y=2) True
Why? @dataclass automatically generates __init__, __repr__, and __eq__. Two Points with the same values are equal (__eq__ compares fields). The default repr is human-readable. This saves writing boilerplate for data-holding classes.
Q 16Multiple Choice
class A:
    def method(self):
        return "A"

class B(A):
    def method(self):
        return super().method() + "B"

class C(B):
    def method(self):
        return super().method() + "C"

print(C().method())
Answer: c) "ABC".

C.method() calls super() → B.method(). B.method() calls super() → A.method() which returns "A". B appends "B" → "AB". C appends "C" → "ABC". Each level calls its parent via super(), building the result up the chain.
Q 17Predict the Output
class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

a = Singleton()
b = Singleton()
print(a is b)
Output
True
Why? __new__ controls object creation (called before __init__). This implements the Singleton pattern — only one instance is ever created. After the first call, _instance is set, so subsequent calls return the same object. a is b confirms they are the exact same object.
Q 18Multiple Choice
class A:
    def __init__(self):
        self.x = 1

a = A()
print(a.__dict__)
Answer: a) {'x': 1}.

__dict__ holds only the instance's own attributes (not class attributes, not methods). self.x = 1 adds x to the instance dict. Class-level things (methods, class attributes) live in A.__dict__. This is how Python's attribute lookup works under the hood.
← Chapter 09: Sets Chapter 11: Iterators & Generators →