Class and Instance Variables in Python
In Python, class and instance variables are important concepts in object-oriented programming (OOP). A class variable is shared across all instances of a class, while an instance variable is specific to each object (or instance) created from the class. Understanding how these variables work is essential for structuring your code effectively and managing data in an object-oriented way.
In this beginner-friendly guide, we’ll explain what class and instance variables are, how they differ, and provide real-life examples.
Focus Keyphrase: Class and Instance Variables
1. Class Variables: What Are They?
A class variable is a variable that is shared by all instances of a class. This means that all objects created from the same class have access to the same class variable, and any changes to the class variable are reflected across all objects.
Example: Class Variable
class Dog:
species = "Canine" # Class variable shared by all Dog objects
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
# Creating Dog objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Bella", 5)
# Accessing class variable and instance variables
print(dog1.species) # Output: Canine
print(dog2.species) # Output: Canine
print(dog1.name) # Output: Buddy
print(dog2.name) # Output: Bella
In this example, the species
variable is a class variable. It is shared by both dog1
and dog2
. Even though each dog has its own name
and age
(instance variables), they share the same species
.
2. Instance Variables: What Are They?
An instance variable is a variable that is unique to each instance (object) of a class. Each object gets its own copy of the instance variables, so changes to the instance variable of one object do not affect other objects.
Example: Instance Variable
class Car:
def __init__(self, brand, model, year):
self.brand = brand # Instance variable
self.model = model # Instance variable
self.year = year # Instance variable
# Creating Car objects
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2021)
# Accessing instance variables
print(car1.brand) # Output: Toyota
print(car2.brand) # Output: Honda
Here, the brand
, model
, and year
are instance variables. Each Car
object has its own set of these variables, and modifying one object’s variables does not affect others.
3. Real-Life Application: Modeling a Library System
Let’s consider a Library class where we have common attributes (like the library name) and specific attributes (like the number of books) for each library branch.
Example: Library System with Class and Instance Variables
class Library:
library_name = "City Library" # Class variable
def __init__(self, branch_name, books):
self.branch_name = branch_name # Instance variable
self.books = books # Instance variable
def display_info(self):
print(f"{self.library_name} - {self.branch_name} Branch")
print(f"Books available: {self.books}")
# Creating library branches
branch1 = Library("Downtown", 1000)
branch2 = Library("Uptown", 500)
# Accessing class and instance variables
branch1.display_info() # Output: City Library - Downtown Branch, Books available: 1000
branch2.display_info() # Output: City Library - Uptown Branch, Books available: 500
In this example, the library_name
is a class variable, shared by all branches of the library. The branch_name
and books
are instance variables, unique to each branch.
4. Common Mistakes and How to Correct Them
Mistake 1: Modifying Class Variables Using Instance Variables
❌ Incorrect Example:
class Dog:
species = "Canine" # Class variable
def __init__(self, name, age):
self.name = name
self.age = age
# Creating Dog objects
dog1 = Dog("Buddy", 3)
# Attempting to modify the class variable using an instance variable
dog1.species = "Feline" # This does not change the class variable
print(Dog.species) # Output: Canine
✅ Fix:
When modifying a class variable, use the class name to change the value, not the instance.
class Dog:
species = "Canine" # Class variable
def __init__(self, name, age):
self.name = name
self.age = age
# Correct way to modify a class variable
Dog.species = "Feline"
print(Dog.species) # Output: Feline
Mistake 2: Confusing Class and Instance Variables
❌ Incorrect Example:
class Person:
species = "Human" # Class variable
def __init__(self, name):
species = "Alien" # Mistake: creating a new local variable, not modifying the class variable
self.name = name
# Creating Person object
person = Person("John")
print(person.species) # Output: AttributeError: 'Person' object has no attribute 'species'
✅ Fix:
When you want to modify the class variable inside a method, use self.__class__.species
or Person.species
.
class Person:
species = "Human" # Class variable
def __init__(self, name):
self.name = name
def change_species(self, new_species):
self.__class__.species = new_species
# Creating Person object
person = Person("John")
person.change_species("Alien")
print(person.species) # Output: Alien
5. Conclusion
In this beginner-friendly guide, we’ve explored class and instance variables in Python. We discussed the difference between these variables, provided examples, and showed how they can be used in real-life applications. Additionally, we highlighted common mistakes like incorrectly modifying class variables and confusing them with instance variables, and provided fixes for those errors.
By understanding how to use class and instance variables, you’ll be able to better structure your Python code, model real-world scenarios, and avoid common pitfalls in object-oriented programming.