Skip to the solution
MediumDSA10 min read

What is the difference between class variables and instance variables?

386 views

The problem

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 on self and 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 = ... or type(self).x = ...).
  • The classic bug: a mutable class variable (members = []) mutated through self is shared by all instances; create it in __init__ instead.
  • self.count += 1 on 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.ClassVar marks 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.

  • oop
  • class-vars

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonShared vs per-object state, __dict__, shadowing and the shared list bug
Pythonself.x += 1, inheritance, type(self) counters and dataclass ClassVar

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 95 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What are generics and TypeVar in Python?

Continue