Course contentsShow
← Python
Lesson 417 of 1,0607. Object-Oriented ProgrammingFree lesson

Distinguishing Between Class and Instance Attributes

Learners will identify when to use shared class-level variables versus unique instance-level variables to optimize memory and data organization.

Distinguishing Between Class and Instance Attributes

In this lesson, you will learn how to differentiate between shared data that belongs to a class and unique data that belongs to an individual object.

The Two Types of Attributes

When building classes, you often need to store information. You have two ways to do this:

  1. Instance Attributes: These are unique to every object. Think of them as the individual details of a specific item, such as a specific user’s username or a bank account’s balance. You define these inside the __init__ method using self.
  2. Class Attributes: These are shared by every single instance of that class. Think of them as global settings or constants for that blueprint, such as a company name or a tax rate that applies to every customer. You define these directly inside the class body, outside of any methods.

Seeing it in Action

Consider a Robot class where every robot has a unique serial number, but they all share the same manufacturer name:

class Robot:
    # Class attribute (shared by all)
    manufacturer = "Cyberdyne Systems"

    def __init__(self, serial_number):
        # Instance attribute (unique to the robot)
        self.serial_number = serial_number

# Creating two unique robots
r1 = Robot(101)
r2 = Robot(102)

print(r1.manufacturer)  # Output: Cyberdyne Systems
print(r2.manufacturer)  # Output: Cyberdyne Systems

print(r1.serial_number) # Output: 101
print(r2.serial_number) # Output: 102

Why Does This Matter?

Using class attributes for shared data is an optimization strategy. Instead of storing the string "Cyberdyne Systems" in memory for every single robot you create, Python stores it once at the class level. This keeps your memory usage lean. Meanwhile, instance attributes ensure that every object maintains its own independent state.

If you find yourself creating a variable that should be identical for every object created from a class, place it at the class level. If the data is specific to an individual object’s state, keep it inside the __init__ constructor as an instance attribute.

Key Takeaway: Use instance attributes for data unique to an object, and class attributes for data shared across all instances to save memory and keep your code organized.