Back to: Python Programming
Class variables are shared among all instances (meaning objects) created from a class.
Instance variables are defined inside the constructor.
Class variables are defined outside of the constructor:

Class variables allow you to share data among all objects created from the class, whilst for instance variables, each object has their own version. With a class variable, all of the objects share one variable.
class Student:
class_year = 2025 # <-- Class variable
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Spongebob", 30)
student2 = Student("Patrick", 35)
print(student1.name)
print(student1.age)
print(student1.class_year) # <-- this works but...
print(Student.class_year) # <-- this is the preferred method
Outputs:
Spongebob
30
2025
2025
You can access the class variable through any one object such as student1 “print(student1.class_year)” or student2 “print(student2.class_year)” – but it is good practice to access a class variable by the name of the class rather than any object created from the class. Hence “print(Student.class_year)” is the preferred way to access a class variable. It helps with clarity and readability, if I am looking at this print statement, I can immediately see that “class_year” is a “class variable” – we are accessing it from the class, not some instance from the class.
We will create a new class variable to keep track of the number of objects that have been made from this class – in this example, how many student objects have been made.
class Student:
class_year = 2025
num_students = 0
def __init__(self, name, age):
self.name = name
self.age = age
Student.num_students += 1
student1 = Student("Spongebob", 30)
student2 = Student("Patrick", 35)
student3 = Student("Squidward", 55)
student4 = Student("Sandy", 27)
print(f"My graduating class of {Student.class_year} has {Student.num_students} students")
print(student1.name)
print(student2.name)
print(student3.name)
print(student4.name)
Outputs:
My graduating class of 2025 has 4 students
Spongebob
Patrick
Squidward
Sandy