Appearance
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)Adefin the body creates a function and stores it in the class. These become methods.(4)The finished class is an object whose type istype.(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 toself.(2)currencyis 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.itemsfinds no instance attribute, so it finds the class's list, andappendchanges 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.
__new__(cls, ...)creates the object and returns it. It is rarely written, because the default fromobjectis almost always enough.__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)Astrcannot be changed after creation, so the cleaning must happen while the string is being created.super().__new__asksstrto 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 realstr, 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 != 0Now 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 byprintand f-strings. If you define only one, define__repr__, becausestr()falls back to it.(3)__eq__defines==. Returning the special valueNotImplementedmeans "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 whyMoney(100) == 100is a cleanFalseand not a crash.(4)Defining__eq__makes Python set__hash__toNone, which would makeMoneyunhashable. 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 equalMoneyvalues collapse into one set member.(5)__add__defines+. Adding a plainintreturnsNotImplemented, which produces the clearTypeErrorat 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 integer0and computes0 + Money(100).intdoes not knowMoney, so Python triesMoney(100).__radd__(0). Returningselffor0is what makessum()work.(7)__mul__handlesprice * 2.(8)__rmul__handles3 * price, where the integer is on the left. Multiplication is symmetric here, so we reuse the same function.(9)__lt__defines<, which is allsorted()needs.functools.total_orderingfrom 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.
- Call
a.__add__(b). If it returns a real value, that is the answer. - If it returns
NotImplemented, orahas no__add__, callb.__radd__(a). - If that also returns
NotImplemented, raiseTypeError.
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__powerslen()and, as you saw in 3.13.2, truthiness.(2)__getitem__powerslines[0]. Because it hands the index straight to a list, negative indexes and slices work too. A slice arrives as asliceobject.(3)__contains__powersin. Here we customise it to search by product code.(4)We never wrote__iter__, yet theforloop works. If a class has no__iter__but has__getitem__, Python falls back to calling__getitem__(0),__getitem__(1)and so on untilIndexError. 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 write | Python 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 = pricegoes 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 writeproduct.price, notproduct.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 whatvars()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 callscls(...)rather thanProduct(...), a subclass that inheritsfrom_dictbuilds 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'ssuper()did not go toNotifier. It went toSmsNotifier, a class thatEmailNotifierknows 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.
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.
- A class always comes before its parents.
- Parents keep the order you listed them in the
classline.EmailNotifierwas listed first, so it comes beforeSmsNotifier. - 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)ListingBasebeforeChilddemands thatBasecome first. ButChildinherits fromBase, soChildmust come beforeBase. 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,__balanceis 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)@abstractmethodmarks 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 forgetschargecannot 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)Onlyxandymay exist on instances, and they are stored at fixed positions inside the object.(2)Adding any other attribute is refused, which also catches typos likepoint.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
classstatement runs its body in a namespace, then callstype(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 remembersobj, so it equalsClass.method(obj, x).selfis 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__. ReturnNotImplementedto 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. _xmeans internal.__xis name mangling to_Class__x, which avoids subclass clashes. An abstract base class refuses to instantiate until every@abstractmethodis 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.