Difference Between Class and Instance Variables in Python

In this tutorial, I will explain the differences between class variables and instance variables in Python. As a Python developer working on a project for New York clients, I came across a scenario where understanding the difference between class and instance variables is important to use in my project. I explored both the variables and I will share my findings in this tutorial with examples.

Class Variables in Python

Class variables are defined within a class but outside of any methods. They are shared across all instances of the class. Class variables can be used to maintain shared state across instances. For example, in a bank account class, you could use a class variable to keep track of the total number of accounts created.

Here’s an example of a class variable in action:

class BankAccount:
    total_accounts = 0  # Class variable

    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance
        BankAccount.total_accounts += 1

In this example, total_accounts is a class variable that keeps track of the number of BankAccount instances created. Every time a new BankAccount is initialized, the total_accounts variable is incremented.

Read How to Validate Passwords in Python?

Instance Variables in Python

Unlike class variables, instance variables are defined within methods. They are unique to each instance of a class. In the BankAccount example above, owner and balance are instance variables. Each BankAccount instance will have its values for these variables.

Let’s expand on the BankAccount example to illustrate instance variables:

class BankAccount:
    total_accounts = 0

    def __init__(self, owner, balance):
        self.owner = owner  # Instance variable
        self.balance = balance  # Instance variable
        BankAccount.total_accounts += 1

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
        else:
            print("Insufficient funds!")

# Creating instances of BankAccount
account1 = BankAccount("John Smith", 1000)
account2 = BankAccount("Jane Doe", 500)

# Accessing instance variables
print(account1.owner) 
print(account2.balance)

# Modifying instance variables
account1.deposit(500)
print(account1.balance) 

account2.withdraw(200)
print(account2.balance) 

Output:

John Smith
500
1500
300

I have executed the above example code and added the screenshot below.

Class and Instance Variables in Python

In this expanded example, each BankAccount instance (account1 and account2) has its own owner and balance instance variables. We can access and modify these variables independently for each instance.

Check out How to Validate Email Addresses in Python?

Key Differences Between Class and Instance Variables in Python

  1. Scope: Class variables are shared among all instances of a class, while instance variables are unique to each instance.
  2. Access: Class variables can be accessed using the class name, whereas instance variables are accessed using the instance name.
  3. Modification: Modifying a class variable affects all instances of the class while modifying an instance variable only affects that specific instance.
  4. Memory Usage: Class variables are stored in the class’s namespace, consuming memory only once. Instance variables are stored in each instance’s namespace, consuming memory for each instance created.

Read How to Use the round() Function in Python?

When to Use Class Variables and Instance Variables in Python?

Use class variables when you need to maintain a shared state across all instances of a class or define constants that are common to all instances. For example:

  • Counting the total number of instances created
  • Storing configuration settings that apply to all instances
  • Defining default values that can be overridden by instances

Use instance variables when you need to store unique data for each instance of a class. For example:

  • Storing individual attributes like name, age, or account balance
  • Maintaining a separate state for each instance
  • Allowing instances to have their behavior based on their specific data

Check out How to Use the Floor() Function in Python?

Example: Student Management System

Let’s consider a real-world example of a student management system for a university in the USA. We’ll define a Student class with both class and instance variables.

class Student:
    total_students = 0  # Class variable

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

    def display_info(self):
        print(f"Name: {self.name}")
        print(f"Student ID: {self.student_id}")
        print(f"Major: {self.major}")

# Creating instances of Student
student1 = Student("Michael Johnson", "S1234", "Computer Science")
student2 = Student("Emily Davis", "S5678", "Business Administration")

# Accessing instance variables
student1.display_info()

student2.display_info()

# Accessing class variable
print(f"Total students: {Student.total_students}") 

Output:

Name: Michael Johnson
Student ID: S1234
Major: Computer Science
Name: Emily Davis
Student ID: S5678
Major: Business Administration
Total students: 2

I have executed the above example code and added the screenshot below.

Difference Between Class and Instance Variables in Python

In this example, the Student class has a class variable total_students that keeps track of the total number of students created. Each Student instance has its instance variables: name, student_id, and major. The display_info method uses the instance variables to display the details of each student.

Check out How to Use Built-In Functions in Python?

Conclusion

In this tutorial, I explained the differences between class variables and instance variables in Python. I discussed what are class and instance variables in Python with an example. I also discussed the key differences between class and instance variables in Python, when to use class and instance variables in Python and an example of a student management system.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.