OOP & the Data Model

Classes in Python — instances and class attributes, methods (instance, class, static), properties, inheritance and the MRO, super(), dunder methods that make objects behave like built-ins, descriptors, slots, ABCs, and metaclasses.

Intermediate 3 min readLesson 4 of 10 Interview Q&A

Python's object model is simple and uniform: classes are objects, functions are objects, and almost every operator or built-in (len(), +, in, for, with, []) is implemented by calling a special ("dunder") method. Implement the right dunders, and your objects work seamlessly with the language. This protocol is the Python data model.

Classes and instances

Python
class Account:
    interest_rate = 0.02                    # class attribute: shared by all instances

    def __init__(self, owner: str, balance: float = 0.0):
        self.owner = owner                  # instance attributes
        self._balance = balance             # _ = internal by convention

    def deposit(self, amount: float) -> None:      # instance method: receives self
        if amount <= 0:
            raise ValueError("amount must be positive")
        self._balance += amount

    @property                               # computed, read-only attribute
    def balance(self) -> float:
        return self._balance

    @classmethod                            # receives the class: alternative constructors
    def from_csv(cls, line: str) -> "Account":
        owner, bal = line.split(",")
        return cls(owner, float(bal))

    @staticmethod                           # plain function namespaced in the class
    def validate_owner(name: str) -> bool:
        return bool(name.strip())

acct = Account.from_csv("ada,100")
acct.deposit(50)
acct.balance          # 150.0 — no parentheses
acct.balance = 0      # AttributeError: no setter

Attribute lookup checks the instance's __dict__, then the class, then base classes. Assigning acct.interest_rate = 0.05 creates an instance attribute that shadows the class one for that instance only.

Python has no true private members. _name signals "internal"; __name triggers name mangling (_Account__name) to avoid clashes in subclasses — not security.

Properties with setters

Python
class Temperature:
    def __init__(self, celsius: float):
        self.celsius = celsius               # goes through the setter

    @property
    def celsius(self) -> float:
        return self._celsius

    @celsius.setter
    def celsius(self, value: float) -> None:
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._celsius = value

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

Start with plain attributes; switch to a property later without changing callers — so Python code doesn't need Java-style getters and setters.

Inheritance, super() and the MRO

Python
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "..."

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)               # call the parent initialiser
        self.breed = breed
    def speak(self):
        return "Woof"

Python supports multiple inheritance. The method resolution order (MRO) — computed by the C3 linearisation algorithm — decides which class's method wins. super() means "the next class in the MRO", not "my parent", which makes cooperative multiple inheritance (mixins) work.

Python
class A:
    def hello(self): return "A"
class B(A):
    def hello(self): return "B>" + super().hello()
class C(A):
    def hello(self): return "C>" + super().hello()
class D(B, C):
    pass

D.__mro__        # (D, B, C, A, object)
D().hello()      # 'B>C>A' — B's super() is C, not A!
objectB,CAD

Mixins are small classes providing one capability (JSONMixin, LoggingMixin) combined via multiple inheritance; keep them stateless and cooperative (always call super()).

Dunder methods: the data model

You writePython calls
repr(x), str(x), f"{x}"__repr__, __str__, __format__
x == y, x < y__eq__, __lt__ (and __le__, __gt__…)
hash(x)__hash__
len(x), bool(x)__len__, __bool__
x[k], x[k] = v, del x[k]__getitem__, __setitem__, __delitem__
k in x__contains__ (falls back to iteration)
for i in x__iter__ / __next__
x + y, x * y, -x__add__, __mul__, __neg__ (and __radd__ for y + x)
x()__call__
with x:__enter__, __exit__
x.attr (missing)__getattr__
Python
from functools import total_ordering

@total_ordering                               # fills in <=, >, >= from __eq__ and __lt__
class Money:
    def __init__(self, cents: int, currency: str = "USD"):
        self.cents, self.currency = cents, currency

    def __repr__(self):                       # unambiguous, for developers
        return f"Money({self.cents}, {self.currency!r})"
    def __str__(self):                        # friendly, for users
        return f"{self.cents / 100:.2f} {self.currency}"

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented             # let Python try the other operand
        return (self.cents, self.currency) == (other.cents, other.currency)
    def __hash__(self):                       # required if you define __eq__ and want hashability
        return hash((self.cents, self.currency))
    def __lt__(self, other):
        return self.cents < other.cents

    def __add__(self, other):
        if other == 0:                        # lets sum() work (it starts from 0)
            return self
        return Money(self.cents + other.cents, self.currency)
    __radd__ = __add__

    def __bool__(self):
        return self.cents != 0

total = sum([Money(150), Money(275)])         # Money(425, 'USD')
sorted([Money(5), Money(2)])

Defining __eq__ without __hash__ makes instances unhashable (__hash__ is set to None) — deliberate, since equal objects must hash equally.

A custom container

Python
class Playlist:
    def __init__(self, songs):
        self._songs = list(songs)
    def __len__(self):
        return len(self._songs)
    def __getitem__(self, index):            # enables indexing, slicing, iteration and 'in'
        return self._songs[index]

p = Playlist(["a", "b", "c"])
len(p), p[0], p[-1], p[1:], "b" in p, list(p)

Descriptors: how properties really work

A descriptor is an object defining __get__ (and optionally __set__/__delete__), stored as a class attribute. Attribute access on instances is routed through it. property, classmethod, staticmethod and even ordinary methods (functions are descriptors that bind self) are built on this.

Python
class Positive:
    def __set_name__(self, owner, name):
        self.name = "_" + name
    def __get__(self, obj, objtype=None):
        return getattr(obj, self.name)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError(f"{self.name[1:]} must be positive")
        setattr(obj, self.name, value)

class Order:
    quantity = Positive()                     # reusable validation logic
    price = Positive()
    def __init__(self, quantity, price):
        self.quantity, self.price = quantity, price

ORMs (Django models, SQLAlchemy columns) use descriptors heavily.

slots

By default each instance stores attributes in a __dict__ (a hash table). __slots__ declares a fixed set of attributes stored in a compact array: less memory, faster access, no accidental new attributes.

Python
class Point:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x, self.y = x, y
# or @dataclass(slots=True)

Abstract base classes and protocols

Python
from abc import ABC, abstractmethod
from typing import Protocol

class Repository(ABC):                       # nominal: subclasses must inherit and implement
    @abstractmethod
    def get(self, id: str): ...

class SupportsClose(Protocol):               # structural: anything with close() matches (static typing)
    def close(self) -> None: ...

The collections.abc module defines ABCs like Iterable, Mapping, Sequence; inherit from MutableMapping and implement five methods to get a full dict-like API for free.

Metaclasses, briefly

Classes are objects too — instances of a metaclass, type by default. class Foo: ... is roughly Foo = type("Foo", bases, namespace). A custom metaclass can intercept class creation (registering subclasses, validating definitions). Most needs are better served by class decorators or __init_subclass__:

Python
class Plugin:
    registry = {}
    def __init_subclass__(cls, name: str, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry[name] = cls

class CsvExporter(Plugin, name="csv"): ...
Plugin.registry   # {'csv': <class 'CsvExporter'>}
Key takeaways
  • Instance attributes live in dict; class attributes are shared; properties replace getters and setters.
  • classmethod for alternative constructors; staticmethod for namespaced helpers.
  • Multiple inheritance follows the C3 MRO; super() calls the next class in the MRO.
  • Dunder methods plug objects into operators and built-ins; return NotImplemented for unsupported operands.
  • Define hash alongside eq; descriptors power properties, methods and ORMs.
  • slots saves memory; prefer init_subclass or decorators over metaclasses.
Interview questions
QWhat is the difference between __str__ and __repr__?easy

repr should return an unambiguous developer-facing representation, ideally valid Python that recreates the object; it's used by the REPL, debuggers and containers. str returns a readable user-facing string for print and str(). If str is missing, Python falls back to repr.

QExplain the MRO and how super() works with multiple inheritance.hard

The method resolution order is a linearisation of a class and its bases computed with C3, preserving local precedence order and monotonicity. Attribute lookup follows it. super() returns a proxy that continues the lookup from the next class after the current one in the MRO of the instance's actual class — so in a diamond, B's super() can be C rather than A, letting every class's method run exactly once in cooperative hierarchies.