In Object-Oriented Programming (OOP), variables inside a class are mainly of two types:
- Instance Variables
- Class Variables
Understanding the difference is very important for writing clean and structured programs.
1. Instance Variables
Instance variables belong to a specific object.
Each object has its own separate copy of instance variables.
They are usually defined inside the constructor using self.
Example
class Student:
def __init__(self, name):
self.name = name # Instance variables1 = Student("Hira")
s2 = Student("Ali")print(s1.name)
print(s2.name)
Output:
Hira
Ali
Here:
s1ands2have their own separatename- Changing one object does not affect the other
Key Points
- Defined using
self - Created when object is created
- Unique for each object
2. Class Variables
Class variables belong to the class itself, not to individual objects.
All objects share the same class variable.
They are defined inside the class but outside the constructor.
Example
class Student:
school = "GIGZ Academy" # Class variable def __init__(self, name):
self.name = names1 = Student("Hira")
s2 = Student("Ali")print(s1.school)
print(s2.school)
Output:
GIGZ Academy
GIGZ Academy
Both objects share the same school value.
Changing Class Variable
Student.school = "W3Skillset"print(s1.school)
print(s2.school)
Now both objects will show the updated value.
Difference Between Instance and Class Variables
Instance Variable
Belongs to object
Separate copy for each object
Defined using self
Created when object is created
Class Variable
Belongs to class
Shared by all objects
Defined directly inside class
Created when class is defined
When to Use Which?
Use Instance Variables when:
- Data is different for each object
- Example: name, age, salary
Use Class Variables when:
- Data is common for all objects
- Example: school name, company name, tax rate
Final Understanding
Instance variables store object-specific data.
Class variables store shared data for all objects of the class.
Both are essential for writing efficient and well-structured OOP programs.