Intermediate Chapter 121 · 25 min read · Module 10: Object-Oriented Programming
Instance Variables
- After this chapter you can explain that instance variables belong to one object.
- You can create instance variables in __init__ and in other methods.
- You can read, change, check and delete instance attributes with dot notation and built-in helpers.
- You can show that changing one object's variable does not affect another.
- You can tell instance variables apart from local variables and from class variables.
Objects exist to hold data. A student object holds a name and marks, a car object holds a speed and a fuel level. This data is stored in instance variables, also called instance attributes. Each object has its own copy, so two students can have different names at the same time.
You have already used instance variables whenever you wrote self.name = name. In this chapter we look at them carefully: where to create them, how to inspect them, and how they behave when objects are copied or changed.
By the end you will be able to design the data of a class with confidence and explain what is stored where.
What is an instance variable?
self.name in a methodAn instance variable is created the first time you assign to self.something. Almost always this is done in __init__, so every object starts with the same set of variables. The value belongs to that object only. Another object of the same class has its own variable with the same name but a separate value.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
s1 = Student("Asha", 80)
s2 = Student("Ravi", 65)
s1.marks = 90
print(s1.name, s1.marks)
print(s2.name, s2.marks)Changing s1.marks did not change s2.marks. The two variables share a name but live in different objects.
Where instance variables live
Python stores the instance variables of an object in a dictionary called __dict__. You can print it with vars(obj) or obj.__dict__. Seeing this dictionary is the best way to understand what an object really contains.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(vars(p))
p.z = 5
print(vars(p))
print(p.__dict__["x"])The second line shows that a new variable z was added after creation. Python allows this, but it is better to define all variables in __init__ so that every object looks the same.
Reading, checking and deleting
Besides dot notation, Python gives three helper functions. getattr(obj, "name", default) reads an attribute by its name and returns the default if it is missing. hasattr(obj, "name") tells you if it exists. setattr(obj, "name", value) creates or changes one. The del statement removes an attribute, after which reading it raises an AttributeError.
class Box:
def __init__(self):
self.size = 10
b = Box()
print(hasattr(b, "size"), hasattr(b, "colour"))
print(getattr(b, "colour", "none"))
setattr(b, "colour", "red")
print(b.colour)
del b.size
print(hasattr(b, "size"))Instance variables versus local variables
A variable created without self. inside a method is local. It disappears when the method finishes. An instance variable keeps its value as long as the object lives. Use instance variables for data that must be remembered between method calls, and local variables for temporary work.
class Tally:
def __init__(self):
self.total = 0
def add(self, n):
temp = self.total + n
self.total = temp
t = Tally()
t.add(5)
t.add(7)
print(t.total)Mutable values inside objects
If an instance variable holds a list or dictionary, then two names for the same list change together. Be careful when you pass a list into a constructor and store it directly: the object and the caller then share that list. Copy it with list(items) when you want the object to have its own.
class Cart:
def __init__(self, items):
self.items = items
mine = ["pen"]
c = Cart(mine)
c.items.append("book")
print(mine)
d = Cart(list(mine))
d.items.append("bag")
print(mine, d.items)Think of an object as a small box with labelled drawers. Each drawer is an instance variable, and the label is its name. When you create a second object, you get a second box with the same labels but its own contents. Nothing you put in one box shows up in the other. This picture is useful whenever you are unsure what a line of code will change.
You should also know that Python looks for a variable in the object first. If the object does not have it, Python then looks in the class. This is why class variables, which you will study in the next chapter, can be read through an object. But when you assign through the object, for example obj.count = 5, Python always creates or changes an instance variable and never changes the class. Keeping this rule in mind avoids many surprises.
| Kind | Created with | Lives |
|---|---|---|
| Instance variable | self.x = ... | as long as the object |
| Local variable | x = ... in a method | until the method ends |
| Class variable | x = ... in the class body | shared by all objects (next chapter) |
self._balance, means internal use only.When designing a class, list the facts that every object must remember, and make each one an instance variable set in __init__. Give them clear names, keep their types consistent, and avoid adding random new variables later from outside the class. This makes your objects predictable and easier to debug.
Python syntax
self.variable = value # inside a method, usually __init__getattr(obj, "name", default)
setattr(obj, "name", value)
hasattr(obj, "name")
del obj.nameReal-world applications
- Storing name, roll number and marks for each student.
- Keeping health, score and position for each game character.
- Holding balance and owner for every bank account.
- Remembering the items inside each shopping cart.
Common mistakes
name = name instead of self.name = name.Fix: Use
self. so the value is saved on the object.Fix: Create all variables in
__init__, or use getattr with a default.Fix: Copy it with
list(items) so the object owns its data.Fix: Store anything that must last as
self.variable.Important tips
- Set every instance variable in
__init__. - Use
vars(obj)while debugging. - Prefix internal names with an underscore.
- Copy mutable arguments you want to keep.
Key points summary
- Instance variables belong to one object.
- They are created by assigning to self.name.
- They are stored in obj.__dict__.
- Locals vanish after the method; instance variables stay.
- Mutable values can be shared by accident.
Exam and interview points
- Instance variables are per object; class variables are shared.
- They are stored in
__dict__. self.x = vcreates or updates one.del obj.xremoves it.
Quick revision
- self.x = v makes an instance variable.
- Each object has its own copy.
- vars(obj) shows them all.
- Locals end with the method.
- Copy lists you want to own.
Frequently asked questions
What is the difference between an instance variable and an attribute?
In everyday use they mean the same thing: a value stored on an object. The word attribute is more general and also includes methods and class variables.
Can I add an instance variable outside the class?
Yes, with `obj.new = value`. It works, but it is better to define variables inside the class so all objects look the same.
How do I see all instance variables?
Use `vars(obj)` or `obj.__dict__`, which return a dictionary of names and values.
What happens if I read a missing attribute?
Python raises AttributeError. Use hasattr or getattr with a default to avoid it.
Do instance variables need to be created in __init__?
No, but that is the best place. Any method can create one, though then the variable exists only after that method runs.
Practise this chapter
19 practice questions Take the chapter quiz