Classes and typing · core
Class attributes, classmethods and super() with mixins
Instance attributes live on each object and class attributes are shared. super() means the next class in the MRO, not the parent, which matters for mixins and for shared-state bugs in web servers.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Instance attributes live in each object's dict. Class attributes live on the class and are shared by all instances.
- Lookup goes instance, then class, then base classes in MRO order. Assigning through self creates an instance attribute that hides the class one. Changing a mutable class attribute through self changes it for everyone.
- A normal method gets self. A classmethod gets cls, so Order.from_row(row) works for subclasses. A staticmethod is a plain function kept in the class namespace.
- new creates the object, init sets it up. _x is private by convention; __x is name-mangled to _ClassName__x, not for security.
- The MRO comes from C3 linearisation: children before parents, left before right, each class once.
- super() means the next class in the MRO of this object's class. In Order(AuditMixin, CacheMixin) with Base, Base.save runs once.
- class Bad(Base, AuditMixin) raises TypeError: Cannot create a consistent method resolution order. If one mixin forgets super(), the chain stops there. Cooperative init passes **kwargs on.
- A privacy incident can come from shared state: recent = [] as a class attribute means every request in one process appends to the same list. Create it in init, use per-request objects, ContextVar in async code, and the user id in every cache key. Ruff rule RUF012 flags it.
The red pen
Common traps: mistake → fix
Mistake: super() calls the parent class
Fix: it calls the next class in the MRO, which may be a sibling.
Mistake: A list as a class attribute is a good default
Fix: it is shared by every instance.
Mistake: __x makes an attribute truly private
Fix: it only renames it.
Mistake: Add a lock to fix users seeing each other's data
Fix: the bug is shared state; the fix is to stop sharing.
Easy to hard
Questions interviewers ask, easy to hard
- What is the difference between a class attribute and an instance attribute?
- When do you use a classmethod and when a staticmethod?
- What does super() do in a class with two mixins? In what order do the save methods run?
- Why does class Bad(Base, AuditMixin) fail?
- Users see each other's recent searches after a release. Where do you look first?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.