Skip to content

Module 11 · Object-Oriented Programming — topic 9 of 25

Instance variables

Data that belongs to one object: creating instance variables in __init__ and methods, their independence between objects, inspecting them with vars(), and keeping them consistent.

Beginner 8 min read·Lesson 166 of 306 in Python Programming

Learning objectives

  • Create and update instance variables
  • Show that instance variables are independent between objects
  • Keep an object's instance variables consistent

Definition

An instance variable is an attribute stored on a specific object, normally created with self.name = value. Each instance has its own copy, so changing it on one object doesn't affect others.

Introduction

Two students share the same class but not the same name or marks. Name and marks are instance variables: data that differs from object to object.

Why it matters

Most of an object's meaningful data lives in instance variables. Managing them carefully — creating them all up front and updating them through methods — keeps objects predictable.

Detailed explanation

Instance variables are created by assigning to self.something, almost always in __init__.

They live in the object's own namespace (obj.__dict__), which vars(obj) returns as a dictionary.

Each object has independent instance variables: a.score = 10 does not change b.score.

Methods update them to keep the object consistent: a withdraw method changes balance and also records the transaction.

Containers stored in instance variables (lists, dicts) must be created per object in __init__, otherwise objects may share them.

Because instance variables can be added to an object at any time, Python will not warn you about a misspelled name: self.scor = 5 silently creates a new attribute instead of updating score. Declaring everything in __init__ makes such typos easier to spot.

Syntax

Python
class Player:
def __init__(self, name):
self.name = name # instance variables
self.score = 0
self.items = []
def collect(self, item, points):
self.items.append(item)
self.score += points
  • Created with self.x = ...
  • One copy per object.
  • Create containers in __init__.

Code examples

Independent state

Python
class Player:
def __init__(self, name):
self.name = name
self.score = 0
p1, p2 = Player("Asha"), Player("Ravi")
p1.score += 50
print(p1.name, p1.score, "|", p2.name, p2.score)
print(vars(p1))
Output
Asha 50 | Ravi 0
{'name': 'Asha', 'score': 50}

Containers per object

Python
class Player:
def __init__(self, name):
self.name = name
self.items = []
a, b = Player("Asha"), Player("Ravi")
a.items.append("sword")
print(a.items, b.items, a.items is b.items)
Output
['sword'] [] False

More examples

Keeping instance variables consistent

Python
class Inventory:
def __init__(self):
self.items = {}
self.total_units = 0
def add(self, name, qty):
self.items[name] = self.items.get(name, 0) + qty
self.total_units += qty
def remove(self, name, qty):
have = self.items.get(name, 0)
if qty > have:
raise ValueError(f"only {have} {name} in stock")
self.items[name] = have - qty
if self.items[name] == 0:
del self.items[name]
self.total_units -= qty
inv = Inventory()
inv.add("pen", 10)
inv.add("book", 3)
inv.remove("pen", 10)
print(inv.items, inv.total_units)
try:
inv.remove("book", 5)
except ValueError as e:
print(e, "| unchanged:", inv.items, inv.total_units)
Output
{'book': 3} 3
only 3 book in stock | unchanged: {'book': 3} 3

Step-by-step explanation

  • items and total_units must always agree, so both are updated together in each method.
  • remove validates before changing anything, so a failed call leaves the object untouched.
  • Empty entries are deleted to keep items tidy.

Expected output

Running “Keeping instance variables consistent” prints exactly:

TextOutput
{'book': 3} 3
only 3 book in stock | unchanged: {'book': 3} 3

Practical applications

  • A shopping cart's items, a player's health, a document's text.
  • An ORM model's field values.

Best practices

  • Declare every instance variable in __init__.
  • Update related variables together in one method.
  • Validate before modifying state.

Common mistakes

Creating instance variables in random methods

Avoid

def start(self):
self.started_at = now() # missing until start() runs

Prefer

def __init__(self):
self.started_at = None

Attributes created later may not exist when other code reads them.

Updating related data separately

Avoid

inv.items["pen"] -= 1 # total_units now wrong

Prefer

inv.remove("pen", 1)

Changing internals directly can break consistency; go through methods.

Important notes

  • Instance variables are also called instance attributes or fields.

Key takeaways

  • Instance variables belong to one object.
  • Create them in __init__ with self.
  • Keep related ones consistent through methods.

Try it yourself

  1. 1
    Write a Thermostat class with current and target temperatures updated through methods.
  2. 2
    Show with vars() how an object's state changes after several method calls.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic