Appearance
Classes and OOP
27. How do classes, __init__ and self work in Python?
The short answer
A class is a blueprint; calling it, Order(7, 4500), creates an instance. Python first creates the empty object with __new__, then calls __init__ to fill in its attributes. self is simply the first parameter of every instance method: the instance the method was called on. order.total_with_vat() is really Order.total_with_vat(order). There is no private keyword: a leading underscore, _balance, signals "internal", and two underscores trigger name mangling to avoid clashes in subclasses.
python
class Order:
def __init__(self, order_id: int, total_pence: int):
self.id = order_id # (1)
self.total_pence = total_pence
def total_with_vat(self) -> int: # (2)
return round(self.total_pence * 1.2)
order = Order(7, 4500)
print(order.total_with_vat()) # 5400
print(Order.total_with_vat(order)) # 5400, the same call (3)- Instance attributes are stored on each object, in its
__dict__. selfis the instance, passed automatically.- Method calls are function calls with the instance as the first argument.
28. What is the difference between class attributes and instance attributes?
The short answer
An instance attribute is set on one object, usually in __init__ as self.items = [], and belongs only to it. A class attribute is defined in the class body and shared by every instance. Reading obj.x looks on the instance first, then on the class. Assigning obj.x = … always creates or changes an instance attribute, hiding the class one. The classic bug is a mutable class attribute, such as items = [] in the class body: every instance appends to the same list.
python
class Cart:
items = []
a, b = Cart(), Cart()
a.items.append("shoes")
print(b.items) # ['shoes'] every cart shares one list
class Cart:
tax_rate = 0.2 # (1) a shared constant: fine
def __init__(self):
self.items = [] # (2) a new list per cart
c = Cart()
c.tax_rate = 0.05 # (3)
print(Cart.tax_rate, c.tax_rate, Cart().tax_rate) # 0.2 0.05 0.2- Immutable shared values are a good use of class attributes.
- Per-object state belongs in
__init__. - Assignment on the instance creates an instance attribute that hides the class one for
conly.
29. What is the difference between instance methods, class methods and static methods?
The short answer
An instance method receives the instance as self and works with its data; it is the default. A class method, @classmethod, receives the class as cls, so it is used for alternative constructors, such as Order.from_csv(line), that also work correctly for subclasses. A static method, @staticmethod, receives neither; it is a plain function that lives in the class's namespace because it belongs there logically. If a static method does not need the class at all, a module-level function is often simpler.
python
class Order:
count = 0
def __init__(self, order_id, total):
self.id, self.total = order_id, total
Order.count += 1
@classmethod
def from_csv(cls, line: str) -> "Order": # (1)
order_id, total = line.split(",")
return cls(int(order_id), int(total))
@staticmethod
def pence_to_pounds(pence: int) -> str: # (2)
return f"£{pence / 100:.2f}"
print(Order.from_csv("7,4500").total) # 4500
print(Order.pence_to_pounds(4500)) # £45.00clsis whichever class it was called on, soGiftOrder.from_csv(…)would build aGiftOrder.- No
selforcls: a helper grouped with the class.
30. How do inheritance, the MRO and super() work?
The short answer
A class can inherit from one or more base classes and override their methods. With multiple inheritance, Python decides where to look for a method using the method resolution order, the MRO, computed by the C3 algorithm: the class itself, then its bases left to right, with each class appearing once and before its own bases. super() calls the next class in the MRO, not simply "the parent", which is what makes cooperative multiple inheritance work: every class calls super() once, and each method in the chain runs exactly once.
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):
def hello(self): return "D>" + super().hello()
print([k.__name__ for k in D.__mro__]) # ['D', 'B', 'C', 'A', 'object']
print(D().hello()) # D>B>C>AReading it: inside B, super() is not A; for a D instance it is the next class in D's MRO, which is C. That is why A.hello runs once, at the end, instead of twice.
Composition over inheritance. Deep inheritance trees are hard to follow. Prefer giving a class the objects it needs, such as passing a PaymentGateway into an OrderService, and use inheritance for real "is a" relationships or small mixins.
31. What are dunder (magic) methods?
The short answer
"Dunder" methods, with double underscores like __len__, are hooks Python calls for built-in operations, so your objects behave like built-in types. __repr__ and __str__ control how an object prints; __eq__ and __hash__ control == and use in sets and dict keys; __lt__ and friends control sorting; __add__ controls +; __len__, __iter__, __getitem__ and __contains__ make container behaviour; __call__ makes an object callable; __enter__ and __exit__ make it a context manager; __bool__ controls truthiness.
python
class Money:
def __init__(self, pence: int):
self.pence = pence
def __add__(self, other: "Money") -> "Money": # (1)
return Money(self.pence + other.pence)
def __str__(self) -> str: # (2)
return f"£{self.pence / 100:.2f}"
def __repr__(self) -> str:
return f"Money({self.pence})"
def __eq__(self, other) -> bool: # (3)
return isinstance(other, Money) and self.pence == other.pence
def __hash__(self) -> int:
return hash(self.pence)
def __bool__(self) -> bool:
return self.pence != 0
print(Money(250) + Money(1000)) # £12.50
print(bool(Money(0))) # False+calls__add__.printuses__str__; the REPL and debuggers use__repr__, which should look like code that recreates the object.- If you define
__eq__, define__hash__too, using the same fields, or the objects cannot be put in sets. Python sets__hash__toNonewhen you define only__eq__.
32. What is @property, and when should you use it?
The short answer
@property makes a method look like an attribute: product.price calls a getter function. A matching @price.setter runs on assignment, which is the place to validate or convert. It lets you start with a plain public attribute and later add logic without changing callers, so Python code does not need Java-style get_price() methods. Use it for cheap computed values and validation; for expensive work, use a method or functools.cached_property so the cost is visible.
python
class Product:
def __init__(self, price_pence: int):
self.price = price_pence # (1) goes through the setter
@property
def price(self) -> int:
return self._price
@price.setter
def price(self, value: int) -> None:
if value < 0:
raise ValueError("price must be >= 0") # (2)
self._price = value
p = Product(100)
p.price = -5 # ValueError: price must be >= 0- Even
__init__uses the setter, so the rule can never be bypassed. - Validation lives in one place.
33. What are dataclasses, and why use them?
The short answer
@dataclass generates the boilerplate for classes that mainly hold data: __init__, __repr__ and __eq__ from type-annotated fields, and optionally ordering, immutability with frozen=True, __slots__ with slots=True, and keyword-only fields. Use field(default_factory=list) for mutable defaults, which avoids the shared-default trap. Dataclasses do not validate types at runtime; for validating external input, such as JSON requests, use Pydantic, which FastAPI is built on.
python
from dataclasses import dataclass, field
@dataclass(order=True)
class LineItem:
sku: str
qty: int = 1
tags: list[str] = field(default_factory=list) # (1)
item = LineItem("A1", 2)
print(item) # LineItem(sku='A1', qty=2, tags=[])
print(item == LineItem("A1", 2)) # True, generated __eq__
print(LineItem("A1") < LineItem("B2")) # True, compares fields in order
@dataclass(frozen=True, slots=True)
class Money: # (2)
pence: int
currency: str = "GBP"- A new list per instance. Writing
tags: list[str] = []raises an error, which protects you from the shared-default bug. frozen=Truemakes instances immutable and hashable; assigning raisesFrozenInstanceError.slots=Truesaves memory (question 34).
| Plain class | @dataclass | Pydantic model | |
|---|---|---|---|
Generated __init__, __repr__, __eq__ | No | Yes | Yes |
| Runtime type validation | No | No | Yes |
| Parse and serialise JSON | No | No | Yes |
| Best for | Behaviour-rich objects | Internal data | API input and output |
34. What does __slots__ do?
The short answer
Normally each instance stores its attributes in a per-object dictionary, __dict__, so you can add any attribute at any time. Declaring __slots__ = ("x", "y") tells Python to reserve fixed storage for exactly those attributes instead. Instances use less memory and attribute access is slightly faster, and assigning any other attribute raises AttributeError. It is worth it when you create very many small objects. @dataclass(slots=True) does it for you.
python
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
Point(1, 2).z = 3
# AttributeError: 'Point' object has no attribute 'z' and no __dict__ for setting new attributesMeasured on CPython 3.14 with tracemalloc, 100,000 instances of a two-attribute class took about 9.2 MB without slots and about 5.3 MB with them.
35. What are abstract base classes and Protocols?
The short answer
An abstract base class, from abc, declares methods with @abstractmethod that subclasses must implement; Python refuses to instantiate a class that has not implemented them all. It is nominal typing: a class must explicitly inherit from the ABC. A Protocol, from typing, describes the methods an object must have, and any class with those methods matches it, without inheriting: this is structural typing, Python's duck typing made checkable by type checkers. Prefer Protocols for "anything that can do X", and ABCs when you want shared base behaviour and enforcement at runtime.
python
from abc import ABC, abstractmethod
from typing import Protocol
class PaymentGateway(ABC):
@abstractmethod
def charge(self, pence: int) -> str: ...
PaymentGateway()
# TypeError: Can't instantiate abstract class PaymentGateway without an implementation for abstract method 'charge'
class SupportsCharge(Protocol): # (1)
def charge(self, pence: int) -> str: ...
class StripeGateway: # (2)
def charge(self, pence: int) -> str:
return "ch_123"
def pay(gateway: SupportsCharge) -> str:
return gateway.charge(100)
pay(StripeGateway()) # accepted by type checkers- The Protocol only describes the shape.
- No inheritance needed. A type checker accepts
StripeGatewaybecause it has a matchingchargemethod.
36. What is the difference between __new__ and __init__, and what is a metaclass?
The short answer
__new__ creates and returns the new instance; it receives the class. __init__ then initialises that instance; it receives self and returns nothing. You rarely override __new__, except to subclass immutable types such as str or tuple, or to control instance creation, as in a singleton. A metaclass is the class of a class: just as calling a class creates an instance, the metaclass creates the class itself, so it can modify or register classes as they are defined. Most needs are better met by class decorators or __init_subclass__, which is simpler.
python
class Base:
registry: list[str] = []
def __init_subclass__(cls, **kwargs): # (1)
super().__init_subclass__(**kwargs)
Base.registry.append(cls.__name__)
class CsvExporter(Base): ...
class JsonExporter(Base): ...
print(Base.registry) # ['CsvExporter', 'JsonExporter']
class Meta(type): # (2)
def __new__(mcls, name, bases, namespace):
cls = super().__new__(mcls, name, bases, namespace)
print("created class", name)
return cls__init_subclass__runs every time a subclass is defined: an easy plug-in registry without a metaclass.- A metaclass's
__new__runs when aclassstatement using it is executed. Frameworks such as Django models and Pydantic use metaclass-like machinery to turn class definitions into fields.