Popular Searches
Popular Course Categories
Popular Courses

Understanding Instance Variables and Class Variables

Understanding Instance Variables and Class Variables

Object-Oriented Programming in Python

Understanding Instance Variables and Class Variables in Python

Course: Python Training

Topic: Understanding Instance Variables and Class Variables

Course Link: Python Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to Instance Variables and Class Variables

Python is an object-oriented programming language that allows developers to organize code using classes and objects. Variables defined within a class help store information about objects and the class itself.

In Python, variables associated with classes are commonly divided into two categories: instance variables and class variables. Understanding the difference between them is essential for designing reusable, maintainable, and efficient object-oriented programs.

Instance variables store data specific to an individual object, whereas class variables store data shared by instances through the class.

Example

class Student:
    school_name = "Bright Future School"  # Class variable

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

student1 = Student("Rahul", 20)
student2 = Student("Priya", 22)

print(student1.name)
print(student2.name)
print(student1.school_name)
print(student2.school_name)

Output:

Rahul
Priya
Bright Future School
Bright Future School

In this example, each student has a different name and age, while both objects access the same class-level school name.

2. Learning Objectives

  • Understand the meaning of instance variables and class variables.
  • Learn how to declare and initialize both types of variables.
  • Understand the role of the self parameter.
  • Differentiate between instance-level and class-level data.
  • Learn how to access and modify variables through objects and classes.
  • Understand variable shadowing and attribute lookup.
  • Apply these concepts through practical Python programs.

3. What Are Instance Variables?

Instance variables are variables associated with a particular object of a class. Each instance can maintain its own value independently of other instances.

Instance variables are generally created inside instance methods using the self parameter. They are commonly initialized inside the __init__() constructor.

Syntax

class ClassName:
    def __init__(self, value):
        self.variable_name = value

Here, self.variable_name represents an instance attribute belonging to the current object.

Example: Creating Instance Variables

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

employee1 = Employee("Amit", 35000)
employee2 = Employee("Neha", 42000)

print(employee1.name)
print(employee1.salary)

print(employee2.name)
print(employee2.salary)

Output:

Amit
35000
Neha
42000

Explanation:

  • name is an instance variable because every employee can have a different name.
  • salary is an instance variable because each employee can earn a different salary.
  • employee1 and employee2 maintain separate values.

4. Characteristics of Instance Variables

  • Object-specific: Each instance can store its own value.
  • Usually initialized using self: This associates the attribute with the current object.
  • Independently modifiable: Updating one object's attribute does not automatically update another object's attribute.
  • Flexible: Instance attributes can also be created in other instance methods when needed.
  • Useful for individual data: They represent properties such as name, age, email, salary, and account balance.

Example: Independent Instance Values

class Car:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color

car1 = Car("Toyota", "White")
car2 = Car("Honda", "Black")

car1.color = "Blue"

print(car1.color)
print(car2.color)

Output:

Blue
Black

Changing car1.color does not change car2.color, because the two objects have separate instance attributes.

5. What Are Class Variables?

Class variables are attributes defined directly inside a class body, outside instance methods. They belong to the class and can be accessed through the class name or through instances.

Class variables are useful when information should be shared among instances, such as a company name, a standard interest rate, a category label, or a common configuration value.

Syntax

class ClassName:
    class_variable = value

Example: Creating a Class Variable

class Employee:
    company_name = "Tech Solutions"

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

employee1 = Employee("Amit")
employee2 = Employee("Neha")

print(Employee.company_name)
print(employee1.company_name)
print(employee2.company_name)

Output:

Tech Solutions
Tech Solutions
Tech Solutions

Explanation: The variable company_name is defined once in the class. Both employee objects can access it without requiring a separate value for each employee.

6. Characteristics of Class Variables

  • Defined at class level: They are written directly inside the class body.
  • Shared through the class: Instances can access the same class-level value when they do not have an overriding instance attribute.
  • Accessible through the class name: For example, Employee.company_name.
  • Useful for common information: They represent data that logically applies to the class as a whole.
  • Can be updated at class level: Assigning a new value through the class name changes the class attribute.

7. Difference Between Instance Variables and Class Variables

Basis Instance Variables Class Variables
Definition Associated with an individual object. Associated with the class.
Declaration Usually declared using self inside an instance method. Declared directly inside the class body.
Storage concept Normally stored in the individual object's attribute dictionary. Normally stored in the class's attribute dictionary.
Value Can differ between objects. Commonly shared when accessed through instances.
Access Usually accessed through an object. Accessed through the class or an instance.
Modification Changes the selected object's attribute. Assignment through the class name changes the class attribute.
Typical examples Student name, employee salary, product price. School name, company name, default category.
Memory behavior Separate attribute values may exist for each instance. One class attribute is defined on the class and can be accessed by many instances.

8. Understanding the Role of self

The self parameter refers to the current instance of a class. It allows an instance method to access and modify attributes belonging to that particular object.

Python passes the instance automatically when an instance method is called through an object.

Example

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

    def display(self):
        print("Student name:", self.name)

student = Student("Rahul")
student.display()

Output:

Student name: Rahul

In this example, self.name refers to the name attribute of the particular student object. If another student object is created, its name can be different.

9. Accessing Instance and Class Variables

Python allows variables to be accessed using either an object or a class, depending on the variable and the intended behavior.

Example

class Product:
    category = "Electronics"

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

product1 = Product("Laptop", 65000)

print(product1.name)
print(product1.price)
print(Product.category)
print(product1.category)

Output:

Laptop
65000
Electronics
Electronics

The object's name and price are instance attributes. The category attribute is found on the class because the instance does not define its own attribute with that name.

10. Modifying Instance Variables

Instance variables can be modified by assigning a new value through a particular object. Other instances remain unchanged unless they share a referenced mutable object or are modified separately.

Example

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

account1 = BankAccount("Amit", 5000)
account2 = BankAccount("Priya", 8000)

account1.balance = 7000

print(account1.balance)
print(account2.balance)

Output:

7000
8000

Only the balance attribute of account1 changes. The balance of account2 remains the same.

11. Modifying Class Variables

A class variable can be modified through the class name. Instances that have not overridden that attribute will then see the updated class-level value.

Example

class Employee:
    company = "ABC Technologies"

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

employee1 = Employee("Amit")
employee2 = Employee("Priya")

Employee.company = "XYZ Technologies"

print(employee1.company)
print(employee2.company)

Output:

XYZ Technologies
XYZ Technologies

Both objects resolve company through the class, so they display the updated value.

12. Attribute Shadowing: Instance Variables and Class Variables With the Same Name

Attribute shadowing occurs when an instance defines an attribute with the same name as a class attribute. For ordinary attribute lookup, the instance's attribute takes precedence over the class attribute.

Example

class Student:
    school = "Green Valley School"

student1 = Student()
student2 = Student()

student1.school = "City Public School"

print(student1.school)
print(student2.school)
print(Student.school)

Output:

City Public School
Green Valley School
Green Valley School

Explanation:

  • Student.school remains "Green Valley School".
  • student1.school now resolves to the instance attribute containing "City Public School".
  • student2.school continues to resolve to the class attribute.

Assigning student1.school creates or updates an instance attribute; it does not modify the class variable. To change the shared class attribute, use Student.school = "New School".

13. Using Class Variables to Count Objects

A class variable can track how many objects have been created. This pattern is useful for simple counters, identifiers, and learning how class-level state works.

Example

class Student:
    student_count = 0

    def __init__(self, name):
        self.name = name
        Student.student_count += 1

student1 = Student("Amit")
student2 = Student("Neha")
student3 = Student("Rahul")

print("Total students:", Student.student_count)

Output:

Total students: 3

Every time the constructor runs, it increments the class variable. Accessing it through Student.student_count makes it clear that the counter belongs to the class.

Important: This is a basic in-memory counter, not a persistent or thread-safe global record. In applications with concurrency, multiple processes, or database-backed records, additional mechanisms may be required.

14. Mutable Class Variables and Shared Data

Class variables can hold mutable objects such as lists, dictionaries, and sets. When instances access the same mutable class attribute, they can modify the same underlying object. This behavior can be useful, but it can also cause unexpected results.

Example: Shared List

class Team:
    members = []

team1 = Team()
team2 = Team()

team1.members.append("Amit")

print(team1.members)
print(team2.members)

Output:

['Amit']
['Amit']

Both instances access the same class-level list. Appending an item through one instance changes the shared list seen by the other.

Safer Approach: Use an Instance Variable

class Team:
    def __init__(self):
        self.members = []

team1 = Team()
team2 = Team()

team1.members.append("Amit")

print(team1.members)
print(team2.members)

Output:

['Amit']
[]

Here, each instance creates its own list. This is the preferred approach when every object needs an independent collection.

15. Using __dict__ to Inspect Variables

For ordinary Python classes without special attribute storage restrictions, the __dict__ attribute can help inspect instance and class attributes.

Example

class Employee:
    department = "IT"

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

employee = Employee("Amit", 40000)

print(employee.__dict__)
print(Employee.__dict__["department"])

Example output:

{'name': 'Amit', 'salary': 40000}
IT

The instance dictionary contains the attributes created on the employee object. The class dictionary contains the class attribute named department, along with other class metadata. The exact representation of a class dictionary includes additional entries that are omitted from this example.

Note: Classes using __slots__ or custom attribute behavior may not expose instance attributes through __dict__ in the same way.

16. Practical Example: Student Management System

This example combines instance variables and class variables in a small student management program.

class Student:
    school_name = "JustAcademy Learning Center"
    total_students = 0

    def __init__(self, name, course, marks):
        self.name = name
        self.course = course
        self.marks = marks
        Student.total_students += 1

    def display_details(self):
        print("Name:", self.name)
        print("Course:", self.course)
        print("Marks:", self.marks)
        print("School:", Student.school_name)

student1 = Student("Amit", "Python", 85)
student2 = Student("Priya", "Data Analytics", 92)

student1.display_details()
print()

student2.display_details()
print()

print("Total students:", Student.total_students)

Output:

Name: Amit
Course: Python
Marks: 85
School: JustAcademy Learning Center

Name: Priya
Course: Data Analytics
Marks: 92
School: JustAcademy Learning Center

Total students: 2

What This Example Demonstrates

  • name, course, and marks are instance variables.
  • school_name is a class variable shared through the class.
  • total_students is a class variable used to count created student objects.
  • The display_details() method accesses the current object's attributes through self.
  • The counter is updated through Student.total_students, making its class-level purpose explicit.

17. Common Mistakes to Avoid

Mistake 1: Forgetting self

class Student:
    def __init__(self, name):
        name = name  # Does not create self.name

Problem: The assignment only assigns the local parameter to itself. It does not create an instance attribute.

Correction:

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

Mistake 2: Accidentally Shadowing a Class Variable

class Employee:
    company = "ABC"

employee = Employee()
employee.company = "XYZ"

print(Employee.company)
print(employee.company)

Output:

ABC
XYZ

Correction: Use Employee.company = "XYZ" if the intention is to update the class attribute for instances that have not created their own attribute with that name.

Mistake 3: Using a Mutable Class Variable for Independent Data

class ShoppingCart:
    items = []

Problem: Every instance accesses the same list unless an instance attribute shadows it.

Correction:

class ShoppingCart:
    def __init__(self):
        self.items = []

Mistake 4: Assuming Every Instance Has a Separate Copy of a Class Variable

A class variable is not automatically copied into every instance. An instance usually accesses the class attribute through Python's attribute lookup unless it has its own attribute with that name.

Mistake 5: Updating a Class Counter Through self

class Student:
    count = 0

    def __init__(self):
        self.count += 1

Problem: If the instance does not already have count, the augmented assignment reads the class value and then assigns a new instance attribute. It will not reliably increment the shared class counter.

Correction:

class Student:
    count = 0

    def __init__(self):
        Student.count += 1

18. Best Practices

  • Use instance variables for data that varies from object to object.
  • Use class variables for data that logically belongs to the class and is shared by its instances.
  • Use the class name to read or update class-level state when the intention is to operate on the class itself.
  • Avoid mutable class variables for data that should be independent for each instance.
  • Choose descriptive names such as company_name, employee_id, and total_students.
  • Keep shared state limited and intentional to make programs easier to maintain.
  • Remember that class variables can be overridden by instance attributes of the same name.
  • Test multiple objects to confirm that updates affect only the intended attributes.

19. Practice Exercises

Exercise 1: Employee Details

Create an Employee class with instance variables for employee name, ID, and salary. Create two objects and display their details.

Exercise 2: Company Name

Add a class variable named company_name. Access it through the class and through two employee objects. Update it through the class name and observe the result.

Exercise 3: Library Management

Create a Book class with instance variables for title and author, and a class variable named library_name. Create three book objects and display their details.

Exercise 4: Object Counter

Create a Product class with a class variable that counts how many product objects have been created. Increment the counter inside the constructor and print the final value.

Exercise 5: Find the Output

class Demo:
    value = 10

obj1 = Demo()
obj2 = Demo()

obj1.value = 20

print(obj1.value)
print(obj2.value)
print(Demo.value)

Expected output:

20
10
10

Explain why changing obj1.value does not change the class attribute or the value accessed by obj2.

20. Interview Questions and Answers

Q1. What is an instance variable in Python?

Answer: An instance variable is an attribute associated with an individual object. It is commonly initialized using self inside the constructor.

Q2. What is a class variable?

Answer: A class variable is an attribute defined directly inside a class body. Instances can access it through the class unless an instance attribute with the same name takes precedence.

Q3. What is the main difference between instance and class variables?

Answer: Instance variables store object-specific information, while class variables represent information associated with the class and commonly shared across its instances.

Q4. Can a class variable be accessed through an object?

Answer: Yes. An object can access a class variable if it does not have an instance attribute with the same name.

Q5. What happens when an instance variable and a class variable have the same name?

Answer: For normal attribute lookup, the instance attribute takes precedence over the class attribute. This is called attribute shadowing.

Q6. How do you modify a class variable?

Answer: Assign a new value through the class name, such as Student.school_name = "New School".

Q7. Can each object have a different value for an instance variable?

Answer: Yes. Each object can maintain its own instance attribute value.

Q8. Why should mutable class variables be used carefully?

Answer: Mutable objects such as lists and dictionaries can be shared across instances. A modification made through one instance may affect what other instances observe.

Q9. How can a class variable count created objects?

Answer: Define a class-level counter and increment it in the constructor using the class name, for example, Student.count += 1.

Q10. Where are instance and class attributes stored?

Answer: In ordinary classes, instance attributes are commonly stored in the instance's __dict__, while class attributes are stored in the class's __dict__. Some Python classes use other storage mechanisms.

21. Quick Revision Checklist

  • Instance variables belong to individual objects.
  • Class variables are defined directly inside the class body.
  • self is used to access and assign instance attributes.
  • Class attributes can be accessed using the class name or an instance.
  • Assigning through an instance can create an instance attribute that shadows a class attribute.
  • Assigning through the class name updates the class attribute.
  • Mutable class attributes can unintentionally share data across instances.
  • Class variables can be used for shared configuration and simple counters.
  • Practice with multiple objects to understand attribute lookup and variable behavior.

22. Conclusion

Instance variables and class variables are fundamental concepts in Python object-oriented programming. Instance variables allow each object to maintain its own state, while class variables represent information associated with the class and accessible to its instances.

By learning how to declare, access, modify, and distinguish these variables, developers can build clearer and more reliable Python applications. Pay particular attention to attribute shadowing, mutable class variables, and the use of the class name when updating shared data.

To continue learning Python programming, explore the JustAcademy Python Training Course, visit the JustAcademy website, or register for a course demo.

whatsapp