Instance vs Class Variables

Understanding what belongs to each object versus what is shared by all.

Introduction

Variables in a class can belong to the class itself or to individual objects. Understanding this difference is crucial -- it determines whether data is unique to each object or shared across all of them.

Instance Variables

Instance variables are defined inside __init__ using self. Each object gets its own separate copy, so changing one does not affect another.

class Dog:
    def __init__(self, name, breed):
        self.name = name      # instance variable
        self.breed = breed    # instance variable

d1 = Dog("Buddy", "Labrador")
d2 = Dog("Max", "Poodle")
print(d1.name)  # Buddy
print(d2.name)  # Max — different!

Key point: Each dog has its own name and breed. Changing d1.name has no effect on d2.name.

Class Variables

Class variables are defined directly in the class body, outside any method. They are shared by all objects of that class.

class Dog:
    species = "Canine"  # class variable

    def __init__(self, name):
        self.name = name  # instance variable

d1 = Dog("Buddy")
d2 = Dog("Max")
print(d1.species)  # Canine
print(d2.species)  # Canine — same!
print(Dog.species)  # Canine — accessed via class too

When to Use Each

Instance Variables

Use for data that is unique to each object.

  • - Name, age, email
  • - Account balance
  • - Individual scores

Class Variables

Use for data shared by all objects.

  • - Species, category
  • - Object count
  • - Default settings

Counting Objects with a Class Variable

A common use for class variables is tracking how many objects have been created.

class Student:
    count = 0  # class variable

    def __init__(self, name):
        self.name = name        # instance variable
        Student.count += 1      # increment shared counter

s1 = Student("Alice")
s2 = Student("Bob")
s3 = Student("Charlie")
print(Student.count)  # 3

Notice: We use Student.count (the class name) to modify the class variable, not self.count. This ensures all objects share the same counter.

Common Pitfall: Modifying via Instance

If you assign to a class variable through an instance, Python creates a new instance variable instead of modifying the class variable. This is a subtle but important trap.

class Dog:
    species = "Canine"

d1 = Dog()
d2 = Dog()

d1.species = "Feline"   # creates a NEW instance variable on d1!
print(d1.species)        # Feline (instance variable)
print(d2.species)        # Canine (still the class variable)
print(Dog.species)       # Canine (class variable unchanged)

OOP Terms

  • Instance Variable: A variable that belongs to a specific object. Defined with self.variable in __init__.
  • Class Variable: A variable that belongs to the class and is shared by all instances. Defined in the class body.
  • Namespace: The scope where a variable lives -- either the object's namespace or the class's namespace.

Best Practices

  • Use class variables only for data that truly applies to every instance (counters, constants, defaults).
  • Always modify class variables through the class name (e.g., Student.count), not through self.
  • Use instance variables for anything that varies between objects.

Common Mistakes

  • Using self.count += 1 instead of ClassName.count += 1 -- this creates a separate instance variable.
  • Putting all variables as class variables when they should be instance variables.
  • Forgetting that mutable class variables (like lists) are shared -- modifying one affects all objects.

Practice Exercises

  1. Create an Employee class with a class variable company = "TechCorp" and instance variables name and role. Create three employees and print each one's company and name.
  2. Add an employee_count class variable that increments each time an employee is created. Print the total after creating three employees.
  3. Experiment with the pitfall: create two objects, change the class variable through one instance, and observe what happens to the other instance and the class itself.

Summary

  • Instance variables belong to individual objects and are defined with self in __init__.
  • Class variables are shared by all objects and are defined directly in the class body.
  • Modify class variables through the class name, not through an instance.
  • Use instance variables for unique data, class variables for shared data.