1. LPU MCA Semester 1
  2. CAB106
  3. Unit 2

CAB106 · Unit 2: Classes and objects

Instance variables, class variables and the self keyword

10 practice questions

Key points

  • Instance variables belong to one object; class variables are shared
  • Assigning through an instance shadows the class attribute
  • self.n += 1 writes an instance attribute
  • Mutable class attributes are shared by all objects

Instance variables are created through self (usually in __init__) and belong to one object. Class variables are defined in the class body and are shared by all instances; read them as ClassName.name or through an instance. Assigning through an instance, as in a.x = 99, creates an instance attribute that shadows the class attribute without changing it.

KindDefinedShared?
Instance variableself.x = ...One object
Class variableIn class bodyAll objects

Lookup checks the instance first, then the class, then its parents. self.n += 1 reads the class value but writes a new instance attribute, so the class variable is unchanged; use ClassName.n += 1 to update the shared value. Mutable class variables such as lists are genuinely shared, so append through any object is seen by all. obj.__dict__ lists an object's own attributes. Rebinding self inside a method only changes the local name.

Exam trap: a mutable class attribute used as per-object storage. Create the list in __init__ instead.

Try two questions

Question 1 · Tier 1, Recall

Which kind of variable stores a single value that all objects built from the same blueprint share?

  1. A class variable
  2. An instance variable
  3. A local variable
  4. A keyword argument
Show the answer

A. A class variable is defined in the class body and shared by all instances.

Why not B: An instance variable belongs to a single object.

Why not C: A local variable exists only inside one function call.

Why not D: A keyword argument is a way of passing a value in a call.