Class Variable and Instance Variable
Python classes can hold two kinds of variables: class variables, which are shared across every object of that class, and instance variables, which hold unique data for each individual object.
Instance Variables
Instance variables are typically defined inside the __init__ method using self, and each object gets its own separate copy.
class Student:
def __init__(self, name):
self.name = name # instance variable
s1 = Student("Abhay")
s2 = Student("Priya")
print(s1.name, s2.name) # Abhay Priya (different for each object)
Class Variables
Class variables are defined directly inside the class body, outside any method, and their value is shared by every instance of the class unless explicitly overridden.
class Student:
institute = "Uncodemy" # class variable, shared by all students
def __init__(self, name):
self.name = name # instance variable, unique per student
s1 = Student("Abhay")
s2 = Student("Priya")
print(s1.institute, s2.institute) # Uncodemy Uncodemy
Changing a class variable through the class itself (e.g.
Student.institute = "New Name") updates it for all instances, whereas assigning it through a specific instance creates a new instance variable that shadows the class variable just for that object.Coming Up Next
Next, you'll learn about constructors and destructors - the special methods that run automatically when an object is created and destroyed.