Assigning Instance Variables to Objects
In this lesson, you will learn how to give each individual object its own unique "memory" so it can track its own state independently of other objects created from the same class.
The Concept of State
When you define a class, you are creating a blueprint. However, a blueprint alone doesn't hold data; it just describes what an object could look like. When you instantiate objects, they start as blank slates. To make them useful, we assign instance variables to them. These are pieces of data attached specifically to one object instance using dot notation (.).
Because these variables are attached to the instance and not the class itself, changing the data in one object has zero impact on another.
Practical Illustration
Imagine we have a Robot class. Every robot needs a name, but each robot has a different one. We assign these values after creating the object:
class Robot:
pass
# Create two individual robot objects
bot1 = Robot()
bot2 = Robot()
# Assign unique instance variables to each
bot1.name = "Alpha"
bot1.battery = 95
bot2.name = "Beta"
bot2.battery = 40
print(bot1.name) # Output: Alpha
print(bot2.name) # Output: Beta
In this example, even though bot1 and bot2 both come from the Robot class, their name and battery values are completely separate. If you were to update bot1.battery, bot2 would remain at 40.
Think of the class as a generic "User Profile" form, and the instance variables as the specific name and email you type into that form. You can fill out ten forms, and each form holds different information, even though they all follow the same structure. By assigning these attributes to specific instances, your programs can manage complex collections of data where each item remembers its own unique history or status.
Key Takeaway: Instance variables allow you to store unique data within individual objects, ensuring that each object maintains its own independent state.