In this lesson, you’ll learn how to store information that belongs to an entire class rather than to any individual object.
The Concept of Shared State
When you define instance variables using self, each object gets its own private copy. If you change self.name on one object, it doesn’t affect the others. However, sometimes you need data that is shared across every single instance—like a counter that tracks how many objects have been created, or a global configuration setting for that specific type of object.
This is where class attributes come in. You define these directly inside the class body, but outside of any methods. Because they belong to the class blueprint itself, every instance of that class can access the exact same value.
Practical Example
Imagine we are building a Robot class and want to keep track of how many robots exist in total. We can use a class attribute to hold this tally:
class Robot:
# This is a class attribute
population = 0
def __init__(self, name):
self.name = name
# Increment the shared class attribute
Robot.population += 1
# Create instances
bot1 = Robot("Alpha")
bot2 = Robot("Beta")
print(Robot.population) # Output: 2
print(bot1.population) # Output: 2 (accessible via instance too!)
In this example, population is not tied to bot1 or bot2. It lives on the Robot class. When bot1 is initialized, it updates the class-level variable. Because every Robot object looks at that same memory location for population, they all see the updated total.
Important Note
While you can access class attributes through an instance (like bot1.population), it is generally best practice to access them through the class name itself (e.g., Robot.population). This makes it visually clear to anyone reading your code that you are modifying a shared value rather than an individual instance variable. If you try to assign a value to self.population = 5, you will accidentally create a new instance attribute that "shadows" the class attribute, which can lead to confusing bugs!
Key Takeaway: Class attributes act as shared variables that maintain a single, consistent state across all instances of a class.