Sitemap

Class Variables in Python

2 min readFeb 12, 2025
Press enter or click to view image in full size
Photo by Hitesh Choudhary on Unsplash

Class variables are variables that are shared among all instances of a class. They are defined within a class but outside any instance methods and are usually used to store data that should be the same across all instances.

Read for free: https://allwin-raju.medium.com/class-variables-in-python-3c27600928ee?sk=9608a4153e5c3bbd9901103a09976725

Defining Class Variables

Class variables are defined at the class level and can be accessed using either the class name or an instance.

class Car:
# Class variable
wheels = 4

def __init__(self, brand, color):
self.brand = brand # Instance variable
self.color = color # Instance variable

# Accessing class variable
print(Car.wheels) # Output: 4

# Creating instances
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")

# Accessing class variable via instance
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4

Modifying Class Variables

  1. Modifying at the Class Level
  • Affects all instances.
Car.wheels = 6  # Changing the class variable

print(car1.wheels) # Output: 6
print(car2.wheels) # Output: 6

2. Modifying at the Instance Level

  • Creates an…

--

--

No responses yet