1️⃣ Class Variable
A class variable is shared by all objects (instances) of the class.
class Student:
school = "ABC School" # Class variableEvery student has access to the same school value.
2️⃣ Instance Variable
An instance variable belongs to a specific object.
Usually, it is created inside __init__() using self.
class Student:
school = "ABC School" # Class variable
def __init__(self, name):
self.name = name # Instance variableNow:
s1 = Student("Tisha")
s2 = Student("Rahul")
print(s1.name) #Tisha
print(s2.name) #Rahul
print(s1.school) #ABC School
print(s2.school) #ABC School⚖️ Difference
Class Variable 🏫 | Instance Variable 👤 |
|---|---|
Belongs to the class | Belongs to an object |
Shared by all instances | Separate for each instance |
Usually defined inside the class | Usually defined using |
|
|