Q&A-1Contrast instance and class attributes for mutable state.
Answer
Core answer. A class attribute lives on the class object and is shared by every instance; an instance attribute lives in that instance's __dict__ and is private to it. Assignment through self.name = value writes the instance __dict__ (unless a data descriptor intercepts it), creating a per-instance attribute that shadows the class one. Mutation through self.name.append(...) is not an assignment: it reads the shared class object and mutates it in place. That asymmetry is why items = [] in a class body becomes an accidental global.
Why lookup behaves that way. obj.attr first walks type(obj).__mro__ looking for a data descriptor (a class attribute defining __set__ or __delete__); if one exists it wins outright. Otherwise Python checks obj.__dict__, then falls back to the class attribute: a plain value or a non-data descriptor. Assignment obj.attr = v skips that walk entirely unless a data descriptor defines __set__; it writes obj.__dict__. Read can reach the class, write never does.
class Cart:
items = [] # one list object, on the class
def __init__(self, owner):
self.owner = owner # instance attribute
a, b = Cart("a"), Cart("b")
a.items.append("apple") # read class attr, mutate it
print(b.items, a.items is b.items) # ['apple'] True
a.items = ["pear"] # assignment -> instance __dict__
print(b.items, a.items is b.items) # ['apple'] FalseTrace: a.items.append finds no data descriptor named items on Cart, finds nothing in a.__dict__, and resolves to the class list. The same object b.items resolves to, so the append is visible to b. a.items = ["pear"] finds no data descriptor, so it writes a.__dict__['items']; from then on a.items stops at the instance dict and b still sees the class list.
| instance attribute | class attribute | |
|---|---|---|
| stored in | obj.__dict__ | type(obj).__dict__ |
| visible to | that instance only | all instances that don't shadow it |
| created by | self.x = v | x = v in the class body |
| mutable default risk | none | shared across instances |
with __slots__ | must be a declared slot | still readable, not assignable |
Alternatives and when to use them. For per-instance mutable state, initialise in __init__ (self.items = []) or use @dataclass with field(default_factory=list). A dataclass with items: list = [] raises ValueError: mutable default <class 'list'> for field items is not allowed at class-definition time, so that trap is caught for you. Use a class attribute deliberately for shared, read-mostly configuration (a default timeout, a registry, a cache keyed by class) and make it immutable (tuple, frozenset, MappingProxyType) when instances must not mutate it. __slots__ removes __dict__ entirely, so a class attribute of the same name becomes read-only from instances: self.items = [...] raises AttributeError.
Failure modes to name. Shared-list bleed between instances (detected by a.items is b.items returning True); the same bug via a mutable default argument, def __init__(self, items=[]), evaluated once at def time; subclass code that assigns a class attribute and silently changes behaviour for the parent's other instances; and __slots__ classes where the class attribute shadows the intended slot. Test construction, equality, and inheritance explicitly: those are where the sharing shows up.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.