Instance Variables and Tracking Object State

🏷️ Object-Oriented Programming (OOP) Basics / Defining a Class

When you create objects from a class, each object needs to keep track of its own unique information. This is where instance variables come in. Think of a class as a blueprint for a house, and each house built from that blueprint has its own color, furniture, and occupants. Instance variables are the individual details that make each object unique.


⚙️ What Are Instance Variables?

Instance variables are attributes that belong to a specific object (instance) of a class. They store data that describes the current state of that object.

  • Each object has its own copy of instance variables
  • They are defined inside the class methods, typically in the constructor method
  • Their values can change over time as the object's state changes
  • They are accessed using the self keyword followed by a dot and the variable name

📊 How Instance Variables Track Object State

The state of an object is simply the collection of all its instance variable values at a given moment. As your program runs, these values can be updated to reflect changes.

  • Initial state is set when the object is first created
  • Current state changes as methods modify the instance variables
  • State tracking allows each object to behave independently from other objects of the same class

🛠️ Creating and Using Instance Variables

Instance variables are created inside the class using the self keyword. The pattern is always: self.variable_name = value

  • The self parameter refers to the current object being worked with
  • You can set instance variables in any method, not just the constructor
  • Instance variables can hold any data type: strings, numbers, lists, dictionaries, or even other objects

🕵️ Example: Tracking a Server Object's State

Consider a simple class that represents a server. Each server object needs to track its own hostname, status, and uptime.

  • hostname stores the server's name
  • status tracks whether the server is running or stopped
  • uptime records how many hours the server has been active

When you create two different server objects, each one maintains its own separate set of these values. Changing the status of one server does not affect the other.


📋 Comparison: Instance Variables vs Local Variables

Feature Instance Variables Local Variables
Scope Available to all methods in the class Only available within the method where defined
Lifetime Lives as long as the object exists Lives only during method execution
Access Accessed with self.variable_name Accessed directly by name
Purpose Track object state over time Temporary calculations or storage

🔄 Updating Object State

The real power of instance variables comes from being able to change them. Methods can modify instance variables to reflect new information about the object.

  • A method can increase a counter variable
  • A method can change a status from "running" to "stopped"
  • A method can update a timestamp to record the last action

Each time an instance variable changes, the object's state is updated accordingly.


✅ Key Takeaways

  • Instance variables make each object unique by storing its own data
  • The self keyword is essential for creating and accessing instance variables
  • Object state is the combined value of all instance variables at any point in time
  • Methods can read and modify instance variables to track changes over time
  • Different objects of the same class operate independently with their own state

By mastering instance variables, you give your objects the ability to remember information and behave intelligently based on their current state. This is the foundation of building meaningful, data-aware programs.


Instance variables store data unique to each object, allowing engineers to track and update individual object state throughout a program.

🔧 Example 1: Creating a Simple Instance Variable

Assigning a value to an object's attribute to store its state.

class Robot:
    def __init__(self):
        self.battery_level = 100

my_robot = Robot()
print(my_robot.battery_level)

📤 Output: 100


🔧 Example 2: Changing Instance Variable Value

Updating an instance variable to reflect a change in object state.

class Robot:
    def __init__(self):
        self.battery_level = 100

my_robot = Robot()
my_robot.battery_level = 75
print(my_robot.battery_level)

📤 Output: 75


🔧 Example 3: Multiple Objects with Independent State

Each object maintains its own copy of instance variables.

class Robot:
    def __init__(self, name):
        self.name = name
        self.battery_level = 100

robot_a = Robot("Alpha")
robot_b = Robot("Beta")
robot_a.battery_level = 60
print(robot_a.name, robot_a.battery_level)
print(robot_b.name, robot_b.battery_level)

📤 Output: Alpha 60
📤 Output: Beta 100


🔧 Example 4: Method That Updates Instance Variable

Using a method to modify an object's state based on an action.

class Robot:
    def __init__(self, name):
        self.name = name
        self.battery_level = 100

    def work(self, hours):
        self.battery_level = self.battery_level - (hours * 10)

worker = Robot("Droid")
worker.work(3)
print(worker.name, worker.battery_level)

📤 Output: Droid 70


🔧 Example 5: Tracking State with Multiple Instance Variables

Using several instance variables to represent different aspects of object state.

class Robot:
    def __init__(self, name):
        self.name = name
        self.battery_level = 100
        self.tasks_completed = 0

    def complete_task(self):
        self.tasks_completed = self.tasks_completed + 1
        self.battery_level = self.battery_level - 15

worker = Robot("Servo")
worker.complete_task()
worker.complete_task()
print(worker.name, worker.tasks_completed, worker.battery_level)

📤 Output: Servo 2 70


📊 Comparison Table: Instance Variable Operations

Operation Example Code Effect on Object State
Create self.battery_level = 100 Sets initial value
Read print(my_robot.battery_level) Accesses current value
Update directly my_robot.battery_level = 75 Changes value externally
Update via method robot.work(3) Changes value through behavior
Multiple variables self.tasks_completed = 0 Tracks different state aspects

When you create objects from a class, each object needs to keep track of its own unique information. This is where instance variables come in. Think of a class as a blueprint for a house, and each house built from that blueprint has its own color, furniture, and occupants. Instance variables are the individual details that make each object unique.


⚙️ What Are Instance Variables?

Instance variables are attributes that belong to a specific object (instance) of a class. They store data that describes the current state of that object.

  • Each object has its own copy of instance variables
  • They are defined inside the class methods, typically in the constructor method
  • Their values can change over time as the object's state changes
  • They are accessed using the self keyword followed by a dot and the variable name

📊 How Instance Variables Track Object State

The state of an object is simply the collection of all its instance variable values at a given moment. As your program runs, these values can be updated to reflect changes.

  • Initial state is set when the object is first created
  • Current state changes as methods modify the instance variables
  • State tracking allows each object to behave independently from other objects of the same class

🛠️ Creating and Using Instance Variables

Instance variables are created inside the class using the self keyword. The pattern is always: self.variable_name = value

  • The self parameter refers to the current object being worked with
  • You can set instance variables in any method, not just the constructor
  • Instance variables can hold any data type: strings, numbers, lists, dictionaries, or even other objects

🕵️ Example: Tracking a Server Object's State

Consider a simple class that represents a server. Each server object needs to track its own hostname, status, and uptime.

  • hostname stores the server's name
  • status tracks whether the server is running or stopped
  • uptime records how many hours the server has been active

When you create two different server objects, each one maintains its own separate set of these values. Changing the status of one server does not affect the other.


📋 Comparison: Instance Variables vs Local Variables

Feature Instance Variables Local Variables
Scope Available to all methods in the class Only available within the method where defined
Lifetime Lives as long as the object exists Lives only during method execution
Access Accessed with self.variable_name Accessed directly by name
Purpose Track object state over time Temporary calculations or storage

🔄 Updating Object State

The real power of instance variables comes from being able to change them. Methods can modify instance variables to reflect new information about the object.

  • A method can increase a counter variable
  • A method can change a status from "running" to "stopped"
  • A method can update a timestamp to record the last action

Each time an instance variable changes, the object's state is updated accordingly.


✅ Key Takeaways

  • Instance variables make each object unique by storing its own data
  • The self keyword is essential for creating and accessing instance variables
  • Object state is the combined value of all instance variables at any point in time
  • Methods can read and modify instance variables to track changes over time
  • Different objects of the same class operate independently with their own state

By mastering instance variables, you give your objects the ability to remember information and behave intelligently based on their current state. This is the foundation of building meaningful, data-aware programs.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

Instance variables store data unique to each object, allowing engineers to track and update individual object state throughout a program.

🔧 Example 1: Creating a Simple Instance Variable

Assigning a value to an object's attribute to store its state.

class Robot:
    def __init__(self):
        self.battery_level = 100

my_robot = Robot()
print(my_robot.battery_level)

📤 Output: 100


🔧 Example 2: Changing Instance Variable Value

Updating an instance variable to reflect a change in object state.

class Robot:
    def __init__(self):
        self.battery_level = 100

my_robot = Robot()
my_robot.battery_level = 75
print(my_robot.battery_level)

📤 Output: 75


🔧 Example 3: Multiple Objects with Independent State

Each object maintains its own copy of instance variables.

class Robot:
    def __init__(self, name):
        self.name = name
        self.battery_level = 100

robot_a = Robot("Alpha")
robot_b = Robot("Beta")
robot_a.battery_level = 60
print(robot_a.name, robot_a.battery_level)
print(robot_b.name, robot_b.battery_level)

📤 Output: Alpha 60
📤 Output: Beta 100


🔧 Example 4: Method That Updates Instance Variable

Using a method to modify an object's state based on an action.

class Robot:
    def __init__(self, name):
        self.name = name
        self.battery_level = 100

    def work(self, hours):
        self.battery_level = self.battery_level - (hours * 10)

worker = Robot("Droid")
worker.work(3)
print(worker.name, worker.battery_level)

📤 Output: Droid 70


🔧 Example 5: Tracking State with Multiple Instance Variables

Using several instance variables to represent different aspects of object state.

class Robot:
    def __init__(self, name):
        self.name = name
        self.battery_level = 100
        self.tasks_completed = 0

    def complete_task(self):
        self.tasks_completed = self.tasks_completed + 1
        self.battery_level = self.battery_level - 15

worker = Robot("Servo")
worker.complete_task()
worker.complete_task()
print(worker.name, worker.tasks_completed, worker.battery_level)

📤 Output: Servo 2 70


📊 Comparison Table: Instance Variable Operations

Operation Example Code Effect on Object State
Create self.battery_level = 100 Sets initial value
Read print(my_robot.battery_level) Accesses current value
Update directly my_robot.battery_level = 75 Changes value externally
Update via method robot.work(3) Changes value through behavior
Multiple variables self.tasks_completed = 0 Tracks different state aspects