DEV Community

Cover image for Python basics - Day 26
Sabin Sim
Sabin Sim

Posted on

Python basics - Day 26

Day 26 – Class Variables vs Instance Variables

Project: Build a “Student Counter System” to understand how class and instance variables differ in memory, behavior, and usage.


01. Learning Goal

By the end of this lesson, you will be able to:

  • Distinguish between class variables and instance variables
  • Understand how each is stored and accessed
  • Recognize when to use one over the other
  • Avoid common mistakes like variable shadowing

02. Problem Scenario

You’re creating a student registration system.

Each student has a unique name, but the total number of registered students should be shared globally.

This problem is best solved using class variables and instance variables together.


03. Step 1 – Instance Variables

Instance variables belong to individual objects.

They are defined inside __init__, and each object keeps its own copy.

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

d1 = Dog("Buddy")
d2 = Dog("Charlie")

print(d1.name)  # Buddy
print(d2.name)  # Charlie
Enter fullscreen mode Exit fullscreen mode

Each instance has its own name, independent of others.


04. Step 2 – Class Variables

Class variables are shared across all instances.
They are defined directly inside the class (outside of any method).

class Dog:
    species = "Canine"   # Class variable

    def __init__(self, name):
        self.name = name

d1 = Dog("Buddy")
d2 = Dog("Charlie")

print(d1.species)  # Canine
print(d2.species)  # Canine
Enter fullscreen mode Exit fullscreen mode

Both objects share the same species value since it belongs to the class itself.


05. Step 3 – Key Difference

Changing an instance variable affects only that object,
while changing a class variable affects all objects (unless overridden).

class Counter:
    count = 0   # Class variable

    def __init__(self):
        Counter.count += 1  # Shared counter for all instances

c1 = Counter()
c2 = Counter()
print(Counter.count)  # 2
Enter fullscreen mode Exit fullscreen mode

Each new instance increases the shared class-level counter.


06. Step 4 – Shadowing (Variable Masking)

Assigning to a class variable via an instance creates a new instance variable,
without changing the class variable.

class Dog:
    species = "Canine"   # Class variable

d1 = Dog()
d2 = Dog()

d1.species = "Feline"   # Creates an instance variable for d1 only
print(d1.species)  # Feline  → instance variable
print(d2.species)  # Canine  → still class variable
print(Dog.species) # Canine  → class-level unchanged
Enter fullscreen mode Exit fullscreen mode

Avoid this if you want to preserve shared class behavior.


07. Step 5 – Practice Examples

Example 1: Student Counter

class Student:
    total_students = 0   # Class variable (shared)

    def __init__(self, name):
        self.name = name  # Instance variable (unique)
        Student.total_students += 1

s1 = Student("Tom")
s2 = Student("Anna")

print("Total students:", Student.total_students)  # 2
Enter fullscreen mode Exit fullscreen mode

Each new instance updates the shared counter.


Example 2: Bank Account

class BankAccount:
    bank_name = "Python Bank"   # Class variable (shared by all accounts)

    def __init__(self, owner, balance):
        self.owner = owner      # Instance variable
        self.balance = balance

a1 = BankAccount("Sabin", 1000)
a2 = BankAccount("Anna", 2000)

print(a1.owner, a1.bank_name)  # Sabin Python Bank
print(a2.owner, a2.bank_name)  # Anna Python Bank
Enter fullscreen mode Exit fullscreen mode

All accounts share the same bank_name,
but each has a unique owner and balance.


08. Mini Project – Student Registry

Build a simple program that tracks the number of registered students.

class StudentRegistry:
    total_students = 0

    def __init__(self, name):
        self.name = name
        StudentRegistry.total_students += 1

    def info(self):
        print(f"Student: {self.name}")

# Register new students
students = [StudentRegistry("Tom"), StudentRegistry("Anna"), StudentRegistry("Liam")]

for s in students:
    s.info()

print("Total registered students:", StudentRegistry.total_students)
Enter fullscreen mode Exit fullscreen mode

Output:

Student: Tom
Student: Anna
Student: Liam
Total registered students: 3
Enter fullscreen mode Exit fullscreen mode

09. Reflection

You have learned how to:

  • Use instance variables for unique object data
  • Use class variables for shared values among all instances
  • Understand the concept of shadowing and how to avoid it
  • Combine both to create flexible and efficient class structures

Next → Day 27 – Encapsulation & Access Control
Learn how to protect data and control access using private attributes and getter/setter methods.

Top comments (0)