Question presented to candidate:
"In a Python class you can put a variable directly in the class body or set it on self inside __init__. What is the difference between class variables and instance variables, how does Python decide which one you get when you read obj.x, and what bug do people hit with them?"
What a strong answer should cover:
- A class variable is defined in the class body and stored once in the class
__dict__, shared by every instance; an instance variable is set onselfand stored in that object's own__dict__. - Lookup order for
obj.x: data descriptors on the type, then the instance__dict__, then the class and its bases along the MRO; so an instance variable shadows a class variable of the same name. - Assignment
obj.x = ...always writes to the instance (it creates a shadow); to change the shared value, assign through the class (Cls.x = ...ortype(self).x = ...). - The classic bug: a mutable class variable (
members = []) mutated throughselfis shared by all instances; create it in__init__instead. self.count += 1on a class variable reads the class value and writes a new instance variable; subclasses inherit class variables until they assign their own.- Typical uses: constants, defaults, counters and caches shared by all instances;
typing.ClassVarmarks them for type checkers and dataclasses.
Clarifying questions expected:
- Should the value be shared by all instances or be per object?
- Will subclasses need their own copy of the shared state?
Code / implementation expected: Yes β a class with one of each, showing __dict__, shadowing, and the shared-list bug with its fix.