- LPU MCA Semester 1
- CAB106
- 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.
| Kind | Defined | Shared? |
|---|---|---|
| Instance variable | self.x = ... | One object |
| Class variable | In class body | All 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
Which kind of variable stores a single value that all objects built from the same blueprint share?
- A class variable
- An instance variable
- A local variable
- 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.