Skip to content

Volume ITechnology

3.13.6 — Classes & the Data Model ​

A billing team stores prices as plain integers of paise, so a ₹450 mug is stored as 45000. One day somebody adds a ₹40 delivery fee, written as 40, to that price. Python happily adds the two numbers, and the customer is charged ₹450.40 instead of ₹490. The fix is a Money class that knows its own unit. But the team wants Money to feel built in: price + fee, price * 3, sum(prices), sorted(prices), print(price) showing ₹450.00. Python lets your own classes do all of that through a set of specially named methods called the data model. This page starts with what a class statement really does, then builds Money and friends step by step, and ends with inheritance, the method resolution order and memory-saving __slots__.

1. The class statement runs ​

Like def, a class statement is not a declaration. It is code that runs, from top to bottom, the moment Python reaches it.

python
print("before class")

class Cart:
    print("  running the class body")     # (1)
    currency = "INR"                       # (2)

    def __init__(self, owner):             # (3)
        self.owner = owner
        self.items = []

    def add(self, sku, price):
        self.items.append((sku, price))

print("after class")
print(type(Cart))                                                  # (4)
print([name for name in Cart.__dict__ if not name.startswith("__")])   # (5)
text
before class
  running the class body
after class
<class 'type'>
['currency', 'add']
  • (1) The body runs like any other block of code, once, when the class is created.
  • (2) A name assigned in the body becomes a class attribute, shared by every instance.
  • (3) A def in the body creates a function and stores it in the class. These become methods.
  • (4) The finished class is an object whose type is type.
  • (5) All the names created by the body end up in the class's namespace dict.

Here is the full story of what happened. Python ran the body in a fresh namespace, which collected currency, __init__ and add. Then it called type("Cart", (object,), namespace) to build the class object from that namespace, and bound the result to the name Cart. 3.13.7 shows you can call type yourself to build a class without a class statement at all.

2. Instances, self and bound methods ​

Calling the class creates an instance. Each instance has its own namespace dict for its own attributes, called __dict__.

python
cart = Cart("asha")
cart.add("mug", 450)

print(cart.__dict__)                     # (1)
print(cart.currency)                     # (2)
text
{'owner': 'asha', 'items': [('mug', 450)]}
INR
  • (1) The instance holds only what __init__ assigned to self.
  • (2) currency is not in the instance. Python looks in the instance first, does not find it, and then looks in the class. Methods are found the same way.

Why self is written out ​

In Java or JavaScript, this appears inside methods by magic. In Python, it is an ordinary first parameter, named self by convention. This is a deliberate design. Python wants methods to be plain functions stored in a class, with nothing hidden. These two calls do exactly the same thing.

python
cart.add("pen", 40)              # (1)
Cart.add(cart, "lamp", 900)      # (2)
print(cart.items)
text
[('mug', 450), ('pen', 40), ('lamp', 900)]
  • (1) The usual way.
  • (2) Look up the plain function on the class and pass the instance yourself. This is what (1) turns into.

How does cart.add know which cart it belongs to? Accessing a function through an instance creates a bound method: a small object that remembers both the function and the instance.

python
add_to_cart = cart.add                         # (1)
print(add_to_cart)
print(add_to_cart.__self__ is cart)            # (2)
print(add_to_cart.__func__ is Cart.add)        # (3)
add_to_cart("notebook", 120)                   # (4)
text
<bound method Cart.add of <__main__.Cart object at 0x0000020AD05E4C20>>
True
True
  • (1) We take the method without calling it.
  • (2) The bound method stores the instance as __self__.
  • (3) And the plain function as __func__.
  • (4) Calling it calls __func__(__self__, "notebook", 120).

Because of this, a bound method is safe to pass around as a callback. It never "forgets" its instance. JavaScript's lost-this bugs from 3.6.3 cannot happen in Python. The mechanism that creates bound methods, on every attribute access, is the descriptor protocol in 3.13.7.

The shared class attribute trap ​

Class attributes are shared by all instances. That is fine for constants like currency. It is a bug for anything mutable.

python
class BadCart:
    items = []                        # (1)

    def add(self, sku):
        self.items.append(sku)        # (2)

first, second = BadCart(), BadCart()
first.add("mug")
print(second.items)                   # (3)
text
['mug']
  • (1) One list, created once when the class body runs, stored on the class.
  • (2) self.items finds no instance attribute, so it finds the class's list, and append changes that one list.
  • (3) Every cart sees every other cart's items.

This is the mutable default argument trap from 3.13.4 wearing a class costume: an object created once and shared by everyone. Per-instance state belongs in __init__, assigned to self.

Notice that assigning is different from mutating. cart.currency = "USD" creates a new attribute on that one instance, which hides the class attribute for that instance only. The class and every other instance still say "INR".

3. __new__ and __init__: creating versus filling in ​

Calling Cart("asha") actually runs two methods.

  1. __new__(cls, ...) creates the object and returns it. It is rarely written, because the default from object is almost always enough.
  2. __init__(self, ...) fills in the object that __new__ returned. It returns nothing.

__init__ is not a constructor in the Java sense. By the time it runs, the object already exists. You need __new__ in the one situation where filling in is too late: when the object is immutable, so its value must be decided at the moment of creation. Here is a product code type that always stores codes in clean upper case.

python
class Sku(str):
    def __new__(cls, raw):
        print(f"  __new__ called with {raw!r}")
        return super().__new__(cls, raw.strip().upper())      # (1)

    def __init__(self, raw):
        print(f"  __init__ called, self is already {self!r}")  # (2)

code = Sku("  mug-blue ")
print(code, isinstance(code, str))                             # (3)
text
  __new__ called with '  mug-blue '
  __init__ called, self is already 'MUG-BLUE'
MUG-BLUE True
  • (1) A str cannot be changed after creation, so the cleaning must happen while the string is being created. super().__new__ asks str to build it with the cleaned value.
  • (2) By the time __init__ runs, the value is fixed. __init__ could not have changed it.
  • (3) It is a real str, so every string method works on it.

Other uses of __new__ include returning a cached instance instead of a new one, and the metaclass machinery in 3.13.7.

4. The data model: making your objects feel built in ​

When Python runs a + b, it does not have special rules for numbers. It calls a.__add__(b). len(x) calls x.__len__(). x[0] calls x.__getitem__(0). print(x) calls x.__str__(). These dunder methods, short for double underscore, are the hooks of the data model. Define them, and your class plugs into the language. Here is the full Money class from the opening, built up one group at a time.

python
class Money:
    def __init__(self, paise):
        self.paise = paise

    def __repr__(self):                                    # (1)
        return f"Money({self.paise})"

    def __str__(self):                                     # (2)
        return f"₹{self.paise / 100:,.2f}"

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

    def __hash__(self):                                    # (4)
        return hash(self.paise)

    def __add__(self, other):                              # (5)
        if isinstance(other, Money):
            return Money(self.paise + other.paise)
        return NotImplemented

    def __radd__(self, other):                             # (6)
        if other == 0:
            return self
        return self.__add__(other)

    def __mul__(self, quantity):                           # (7)
        if isinstance(quantity, int):
            return Money(self.paise * quantity)
        return NotImplemented

    __rmul__ = __mul__                                     # (8)

    def __lt__(self, other):                               # (9)
        return self.paise < other.paise

    def __bool__(self):                                    # (10)
        return self.paise != 0

Now see what it can do, and then the walk-through of each method.

python
price = Money(45000)

print(repr(price), str(price), [price])
print(price + Money(500), price * 2, 3 * price)
print(sum([Money(100), Money(250)]))
print(Money(100) == Money(100), Money(100) == 100, {Money(1), Money(1)})
print(sorted([Money(300), Money(100)]), bool(Money(0)))

try:
    price + 5
except TypeError as error:
    print("TypeError:", error)
text
Money(45000) ₹450.00 [Money(45000)]
₹455.00 ₹900.00 ₹1,350.00
₹3.50
True False {Money(1)}
[Money(100), Money(300)] False
TypeError: unsupported operand type(s) for +: 'Money' and 'int'
  • (1) __repr__ is the developer's view, shown in the REPL, in debuggers and inside lists. The convention is to make it look like the code that would recreate the object.
  • (2) __str__ is the user's view, used by print and f-strings. If you define only one, define __repr__, because str() falls back to it.
  • (3) __eq__ defines ==. Returning the special value NotImplemented means "I do not know how to compare with that". Python then tries the other object's __eq__, and if that also gives up, falls back to identity. That is why Money(100) == 100 is a clean False and not a crash.
  • (4) Defining __eq__ makes Python set __hash__ to None, which would make Money unhashable. We restore it, hashing the same field that __eq__ compares. That keeps the contract from 3.13.3: equal objects have equal hashes. Now two equal Money values collapse into one set member.
  • (5) __add__ defines +. Adding a plain int returns NotImplemented, which produces the clear TypeError at the end. That is exactly the bug from the opening, now caught.
  • (6) __radd__ is the reflected add. Python calls it when the left operand gave up. sum() starts from the integer 0 and computes 0 + Money(100). int does not know Money, so Python tries Money(100).__radd__(0). Returning self for 0 is what makes sum() work.
  • (7) __mul__ handles price * 2.
  • (8) __rmul__ handles 3 * price, where the integer is on the left. Multiplication is symmetric here, so we reuse the same function.
  • (9) __lt__ defines <, which is all sorted() needs. functools.total_ordering from 3.13.5 could fill in <=, > and >=.
  • (10) __bool__ makes zero money falsy, following the truthiness rules from 3.13.2.

How Python evaluates a + b ​

The NotImplemented dance deserves a precise statement, because it explains every operator.

  1. Call a.__add__(b). If it returns a real value, that is the answer.
  2. If it returns NotImplemented, or a has no __add__, call b.__radd__(a).
  3. If that also returns NotImplemented, raise TypeError.

There is one twist. If b's type is a subclass of a's type and overrides the reflected method, Python tries b.__radd__(a) first. That lets a more specialised type take control.

Container methods ​

A second group of dunder methods makes an object behave like a collection. Here is an order's lines, wrapped in a class that hides the underlying list.

python
class OrderLines:
    def __init__(self, lines):
        self._lines = list(lines)

    def __len__(self):                       # (1)
        return len(self._lines)

    def __getitem__(self, index):            # (2)
        return self._lines[index]

    def __contains__(self, sku):             # (3)
        return any(line_sku == sku for line_sku, _ in self._lines)

lines = OrderLines([("mug", 2), ("pen", 5), ("lamp", 1)])
print(len(lines), lines[0], lines[-1], lines[1:])
print("pen" in lines)
for line in lines:                           # (4)
    print("  ", line)
text
3 ('mug', 2) ('lamp', 1) [('pen', 5), ('lamp', 1)]
True
   ('mug', 2)
   ('pen', 5)
   ('lamp', 1)
  • (1) __len__ powers len() and, as you saw in 3.13.2, truthiness.
  • (2) __getitem__ powers lines[0]. Because it hands the index straight to a list, negative indexes and slices work too. A slice arrives as a slice object.
  • (3) __contains__ powers in. Here we customise it to search by product code.
  • (4) We never wrote __iter__, yet the for loop works. If a class has no __iter__ but has __getitem__, Python falls back to calling __getitem__(0), __getitem__(1) and so on until IndexError. That is an old protocol kept for compatibility. New code should define __iter__, explained in 3.13.9.

A map of the main dunder methods ​

You writePython calls
repr(x), str(x)__repr__, __str__
x == y, x < y__eq__, __lt__
hash(x)__hash__
x + y, y + x__add__, __radd__
x += y__iadd__
len(x), bool(x)__len__, __bool__
x[k], x[k] = v__getitem__, __setitem__
k in x__contains__
for v in x__iter__
x(...)__call__
with x:__enter__, __exit__
x.name__getattribute__, __getattr__

The last row is the deepest hook of all, and it gets its own page in 3.13.7.

Dunder methods are looked up on the class ​

One expert detail explains several puzzles. When Python runs len(x), it looks for __len__ on type(x), not on the instance.

python
class Order:
    def __len__(self):
        return 3

order = Order()
order.__len__ = lambda: 99           # (1)
print(len(order), order.__len__())   # (2)
text
3 99
  • (1) We attach a different __len__ to the instance itself.
  • (2) len() ignores it and uses the class's method. Calling the attribute directly finds the instance's version.

This is deliberate. Skipping the instance makes every operator faster, and it guarantees that all objects of one class behave the same way under + or len.

5. @property, @classmethod and @staticmethod ​

Three built-in decorators change how a method is called. 3.13.7 shows how each one works inside. Here is what each one is for.

python
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price                       # (1)

    @property
    def price(self):                             # (2)
        return self._price

    @price.setter
    def price(self, value):                      # (3)
        if value < 0:
            raise ValueError("price cannot be negative")
        self._price = value

    @classmethod
    def from_dict(cls, data):                    # (4)
        return cls(data["name"], data["price"])

    @staticmethod
    def is_valid_sku(code):                      # (5)
        return code.isalnum() and len(code) == 8

product = Product.from_dict({"name": "mug", "price": 450})
print(product.price, vars(product))

try:
    product.price = -5
except ValueError as error:
    print("ValueError:", error)

print(Product.is_valid_sku("MUG00001"))
text
450 {'name': 'mug', '_price': 450}
ValueError: price cannot be negative
True
  • (1) Even inside __init__, self.price = price goes through the setter, so the check runs from the very first assignment.
  • (2) A property is a method that is read like an attribute. Callers write product.price, not product.price().
  • (3) The setter runs on every assignment, so every place that sets a price is checked. The real value is stored as _price, which is what vars() shows.
  • (4) A class method receives the class as its first argument, cls, instead of an instance. Its main use is an alternative constructor: another way to build an instance. Because it calls cls(...) rather than Product(...), a subclass that inherits from_dict builds an instance of the subclass.
  • (5) A static method receives neither. It is a plain function that lives in the class because it belongs there logically.

Properties solve a real problem from other languages. In Java, teams write getPrice() and setPrice() for every field "in case we need validation later". In Python you start with a plain attribute. If you need validation later, you turn it into a property, and every caller's product.price keeps working without a single change.

6. Inheritance, super() and the MRO ​

A class can inherit from another. The child gets all of the parent's attributes and methods and can override any of them by defining its own version. super() lets an overriding method call the version it replaced.

With single inheritance this is straightforward. Python also allows multiple inheritance, and that raises a real question. If a class has two parents, and both define send, which one runs, and in what order? Here is a notification system where an order update can go out by email and by SMS.

python
class Notifier:
    def send(self, message):
        print(f"Notifier: {message}")

class EmailNotifier(Notifier):
    def send(self, message):
        print("Email: formatting")
        super().send(message)                    # (1)

class SmsNotifier(Notifier):
    def send(self, message):
        print("SMS: shortening")
        super().send(message)

class AllChannels(EmailNotifier, SmsNotifier):  # (2)
    def send(self, message):
        print("All: start")
        super().send(message)

AllChannels().send("Order shipped")
print([cls.__name__ for cls in AllChannels.__mro__])   # (3)
text
All: start
Email: formatting
SMS: shortening
Notifier: Order shipped
['AllChannels', 'EmailNotifier', 'SmsNotifier', 'Notifier', 'object']
  • (1) Look carefully at the output. EmailNotifier's super() did not go to Notifier. It went to SmsNotifier, a class that EmailNotifier knows nothing about.
  • (2) The class inherits from both. This shape, where two parents share a grandparent, is called the diamond.
  • (3) The method resolution order, or MRO, is the single list Python follows when it looks up any attribute on this class.

So super() does not mean "my parent". It means "the next class in the MRO of the object I was called on". For an AllChannels object, the class after EmailNotifier is SmsNotifier. That is why each class ran exactly once, and why Notifier's method ran only once at the end, even though two classes inherit from it. Figure 1 shows the diamond and the order.

① AllChannels② EmailNotifier③ SmsNotifier④ Notifier⑤ objectsuper() follows the amber path
Figure 1 — The diamond and its MRO. Grey lines show who inherits from whom. The amber path is the order that super() follows for an AllChannels object: each class once, and the shared parent last.

How the MRO is computed: C3 linearisation ​

Python computes the MRO with an algorithm called C3 linearisation, adopted in Python 2.3 after a paper from the Dylan language community. It guarantees three things.

  1. A class always comes before its parents.
  2. Parents keep the order you listed them in the class line. EmailNotifier was listed first, so it comes before SmsNotifier.
  3. Each class appears exactly once.

Sometimes those rules cannot all be satisfied, and Python refuses to create the class.

python
class Base: pass
class Child(Base): pass

try:
    class Broken(Base, Child): pass        # (1)
except TypeError as error:
    print("TypeError:", error)
text
TypeError: Cannot create a consistent method resolution order (MRO) for bases Base, Child
  • (1) Listing Base before Child demands that Base come first. But Child inherits from Base, so Child must come before Base. Both cannot be true.

Cooperative super() and mixins ​

The diamond only works because every send calls super().send(...). If EmailNotifier skipped that call, SmsNotifier would silently never run. This style is called cooperative multiple inheritance: every class in the chain agrees to pass the call along. It also means every method in the chain should accept the same arguments, or accept **kwargs and pass along what it does not use.

The most common, and safest, use of multiple inheritance is the mixin: a small class that adds one feature and is not meant to be used on its own. A JsonMixin with a to_json method, mixed into several model classes, is the typical example. Django's class-based views are built almost entirely from mixins. If you find yourself drawing a diamond with state in several classes, consider composition instead: an AllChannels object that holds a list of notifiers and calls each one. Part 9 compares these designs in depth.

7. Privacy by convention, and name mangling ​

Python has no private keyword. It uses naming conventions instead, and one small mechanism.

  • A single leading underscore, _internal, means "this is internal, please do not use it from outside". Nothing enforces it, but linters, editors and every Python developer respect it. from module import * also skips such names.
  • A double leading underscore, __balance, triggers name mangling. Python renames the attribute to include the class name.
python
class Account:
    def __init__(self):
        self.__balance = 100        # (1)
        self._internal = 1

account = Account()
print(vars(account))                # (2)

try:
    account.__balance
except AttributeError as error:
    print("AttributeError:", error)

print(account._Account__balance)    # (3)
text
{'_Account__balance': 100, '_internal': 1}
AttributeError: 'Account' object has no attribute '__balance'
100
  • (1) Inside the class body, __balance is rewritten by the compiler to _Account__balance.
  • (2) You can see the renamed attribute.
  • (3) It is still reachable if you spell out the mangled name. This is not security.

Name mangling exists for one purpose: to stop a subclass from accidentally overwriting a parent's attribute of the same name, because each class's __x gets a different mangled name. For ordinary "please do not touch" fields, a single underscore is the Python norm. The Python saying is "we are all consenting adults here".

8. Abstract base classes ​

Sometimes a class exists only to define what its subclasses must provide. A payment module might support several gateways, and each must have a charge method. An abstract base class, or ABC, makes that rule enforceable.

python
from abc import ABC, abstractmethod

class PaymentGateway(ABC):
    @abstractmethod
    def charge(self, order_id, paise):              # (1)
        ...

    def charge_with_log(self, order_id, paise):     # (2)
        print(f"charging {order_id}")
        return self.charge(order_id, paise)

class Razorpay(PaymentGateway):
    def charge(self, order_id, paise):
        return f"rzp_{order_id}"

class Unfinished(PaymentGateway):
    pass

print(Razorpay().charge_with_log("ORD-1", 500))
try:
    Unfinished()                                    # (3)
except TypeError as error:
    print("TypeError:", error)
text
charging ORD-1
rzp_ORD-1
TypeError: Can't instantiate abstract class Unfinished without an implementation for abstract method 'charge'
  • (1) @abstractmethod marks a method every concrete subclass must override.
  • (2) An ABC can still contain normal methods that use the abstract ones. This is the template method pattern you will meet in Part 9.
  • (3) A subclass that forgets charge cannot be instantiated. The error appears when you create the object, not later when somebody calls the missing method.

ABCs require inheritance. 3.13.12 shows typing.Protocol, which describes the same requirement structurally. Any class with a matching charge method fits, with no inheritance needed, which is the same idea as TypeScript's structural types.

9. __slots__: smaller, stricter objects ​

By default each instance has its own __dict__, so you can add any attribute at any time. That flexibility costs memory. __slots__ replaces the dict with a fixed set of named slots, much like a C struct.

python
import tracemalloc

class PointWithDict:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class PointWithSlots:
    __slots__ = ("x", "y")                              # (1)
    def __init__(self, x, y):
        self.x = x
        self.y = y

for cls in (PointWithDict, PointWithSlots):
    tracemalloc.start()
    points = [cls(i, i) for i in range(100_000)]
    used, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    print(f"{cls.__name__}: {used / 1e6:.1f} MB")

point = PointWithSlots(1, 2)
try:
    point.z = 3                                         # (2)
except AttributeError as error:
    print("AttributeError:", error)
text
PointWithDict: 12.8 MB
PointWithSlots: 8.8 MB
AttributeError: 'PointWithSlots' object has no attribute 'z' and no __dict__ for setting new attributes
  • (1) Only x and y may exist on instances, and they are stored at fixed positions inside the object.
  • (2) Adding any other attribute is refused, which also catches typos like point.xx = 5.

The saving here is about 40 bytes per object, roughly 30%, and attribute access is slightly faster. Since Python 3.11, ordinary instances already store their attributes more compactly than before, so the gap is smaller than old blog posts claim. Use __slots__ when you create millions of small objects, such as rows, points or events. For ordinary classes the flexibility of __dict__ is worth more. A @dataclass(slots=True) from 3.13.8 writes the slots for you.

What the interviewer will push on ​

"What is the difference between __new__ and __init__?" They are checking whether you know object creation has two steps. __new__ creates and returns the instance, and __init__ fills it in and returns None. The tell is knowing when you need __new__: subclassing an immutable type such as str, int or tuple, or controlling which instance is returned. The wrong answer is "__init__ is the constructor".

"Why does Python make you write self?" Methods are plain functions stored in a class. obj.method(x) becomes Class.method(obj, x) through a bound method. Writing self makes that explicit and lets functions and methods share one model. Bonus: this is why bound methods never lose their instance, unlike JavaScript's this.

"What is the MRO, and what does super() actually call?" The MRO is the C3-linearised list of classes used for attribute lookup. super() calls the next class in the MRO of the instance's class, not necessarily the parent. Show the diamond. The common wrong answer is "super calls the parent class".

"If you define __eq__, what happens to __hash__?" Python sets __hash__ to None, making instances unhashable, because the default identity hash would break the rule that equal objects hash equally. Define __hash__ on the same fields, and only if the object is effectively immutable.

"@classmethod versus @staticmethod?" A class method receives the class and is used for alternative constructors that respect subclassing. A static method receives nothing and is a namespaced function. A strong answer adds that from_dict on a subclass builds the subclass.

Something to volunteer that nobody asks for: returning NotImplemented, not raising TypeError, from a binary dunder method lets Python try the other operand's reflected method. That is how sum() works on your class, through __radd__ with 0, and why Money(1) == 1 is a clean False.

Recall

  • A class statement runs its body in a namespace, then calls type(name, bases, namespace). Names in the body are class attributes, shared by all instances. Mutable class attributes are a shared-state bug.
  • obj.method(x) creates a bound method that remembers obj, so it equals Class.method(obj, x). self is just the first parameter.
  • __new__ creates the object, and __init__ fills it in. You need __new__ for immutable subclasses.
  • Dunder methods plug a class into the language: __repr__/__str__, __eq__/__hash__, __add__/__radd__, __len__, __getitem__, __contains__, __iter__, __call__. Return NotImplemented to let the other operand try. Python looks dunders up on the class, not the instance.
  • Property = validated attribute access. Class method = gets cls, used for alternative constructors. Static method = plain function in the class.
  • The method resolution order comes from C3 linearisation: child before parents, parents in listed order, each class once. super() means the next class in the instance's MRO. Prefer mixins and composition.
  • _x means internal. __x is name mangling to _Class__x, which avoids subclass clashes. An abstract base class refuses to instantiate until every @abstractmethod is implemented. __slots__ removes the per-instance dict and saves memory.

Self-test: Why did EmailNotifier's super().send() call SmsNotifier? What makes sum([Money(1), Money(2)]) work? Why does len(obj) ignore an __len__ attached to the instance? What would break if Money defined __eq__ without __hash__?

Quiz Bank ​

FoundationalWhat is the difference between __repr__ and __str__?

__repr__ is the developer's view, used by the REPL, debuggers, logging of containers and repr(). The convention is an unambiguous string, ideally looking like code that recreates the object, such as Money(45000). __str__ is the user-facing view used by print(), str() and f-strings, such as ₹450.00. If a class defines only __repr__, str() falls back to it. If it defines only __str__, the REPL still shows the unhelpful default repr. So always define __repr__ first.

AppliedA subclass calls Base.__init__(self) directly instead of super().__init__(). Everything works until someone uses the class in multiple inheritance. What breaks?

Calling Base.__init__(self) by name hard-codes the next step and skips the MRO. In a diamond, the class that should run between this one and Base according to the MRO is never initialised. And if two classes both call the shared base by name, the base's __init__ runs twice, which can reset state or open resources twice. super().__init__() follows the instance's MRO, so each class in the hierarchy runs exactly once, in the C3 order. The fix is to use super() consistently in every class of the hierarchy and to pass on unused keyword arguments with **kwargs.

InterviewMake a class usable in a for loop, with len(), in, and indexing. Which methods do you need and why?

Define __len__ for len() and truthiness. Define __getitem__ for indexing and slicing, and handle slice objects if you are not forwarding to a list. Define __contains__ for a fast in, because without it Python falls back to iterating and comparing each item. And define __iter__ returning an iterator for for loops. Without __iter__ Python uses the legacy protocol of calling __getitem__ with 0, 1, 2 until IndexError, which works but is slower and fails for non-integer keys. Inheriting from collections.abc.Sequence and implementing only __len__ and __getitem__ gives you __contains__, __iter__, index and count as ready-made methods.

StaffYour domain model has an Order class with 40 attributes and 25 methods, inheriting from three mixins. New engineers cannot follow it. How do you approach the redesign?

First draw the MRO and list which mixin owns which state. Deep cooperative inheritance with state in several classes is the usual source of confusion, because behaviour depends on an ordering nobody can see in one file. Then split by responsibility. Pure data, such as identifiers, lines, totals and status, becomes a small dataclass or Pydantic model. Behaviour that varies, such as pricing, tax and notifications, moves into separate objects that the order is given and calls, which is composition rather than inheritance. Keep mixins only for small, stateless features such as serialisation. Make status changes go through explicit methods that check what is allowed. The result is several short classes whose relationships are visible in their constructors instead of hidden in an MRO.

Next: this page used @property, bound methods and super() as if by magic. 3.13.7 removes the magic. It walks the exact algorithm Python runs for every obj.name, and shows that methods, properties and class methods are all one mechanism called the descriptor protocol.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet