Skip to the page

Python OOP and typing · Concept

Class attributes, instance attributes, classmethod and staticmethod

The interviewer asks

What's the difference between a class attribute and an instance attribute? And between a normal method, a @classmethod and a @staticmethod? When do you use each?

Then

Follow-ups the interviewer asks next

  1. What's the difference between __init__ and __new__?
  2. Why are alternate constructors written as classmethods?
  3. What does a name with two leading underscores (__x) do?
  4. What's in obj.__dict__, and what's in type(obj).__dict__?

The answer

What a strong answer covers

  • Instance attributes live in each object's __dict__; class attributes live on the class and are shared.
  • Lookup goes instance, then class, then base classes (the MRO). Assigning through self creates an instance attribute that hides the class one; mutating 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 too; 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 to avoid clashes in subclasses, not for security.

The red pen

Common traps

Avoid:a list as a class attribute "as a default"; thinking __x makes something truly private.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview