Python class variables are a struc­tured way of sharing data between different instances of a class. If you make changes to a class variable, it affects all instances of the class. This means you don’t have to redefine them each time they are in­stan­ti­at­ed.

What are Python class variables?

In Python, we create class variables within a class. Unlike instance variables, which are specific to each instance of a class, class variables retain the same value for all instances. Class variables are typically set up before the con­struc­tor and can be accessed by any instance of the class.

Python class variables are useful for storing data that applies to all instances of a class, such as con­fig­u­ra­tion settings, default values or shared states across a class hierarchy. Class variables also allow you to define class methods or at­trib­ut­es that every instance can access, enhancing both the func­tion­al­i­ty and the structure of your code.

Web Hosting
Hosting that scales with your ambitions
  • Stay online with 99.99% uptime and robust security
  • Add per­for­mance with a click as traffic grows
  • Includes free domain, SSL, email, and 24/7 support

What is the syntax of Python class variables?

Python class variables are created within the class de­f­i­n­i­tion and outside of methods.

class Car:
    total_cars = 0  # Class variable to track the total number of cars
    def __init__(self, brand, model):
        self.brand = brand  # Instance variable for the car brand
        self.model = model  # Instance variable for the car model
        Car.total_cars += 1  # Increment the total number of cars upon each instantiation
    def display_details(self):
        print(f"Brand: {self.brand}, Model: {self.model}")
# Creating instances of Car
car1 = Car("BMW", "X3")
car2 = Car("Audi", "A4")
# Accessing class variable and instance variables
print(f"Total number of cars: {Car.total_cars}")  # Output: 2
car1.display_details()  # Output: Brand: BMW, Model: X3
car2.display_details()  # Output: Brand: Audi, Model: A4
python

Within the class Car we define the class variable total_cars to keep track of the total number of cars. The con­struc­tor __init__ is called when a new instance of the class is created. At each in­stan­ti­a­tion, the instance variables brand and model are set and the class variable total_cars is in­cre­ment­ed by 1.

By calling the display_details() method, we can display the details of the re­spec­tive car instances. In an f-string, a Python string format method, we can access the class variable total_cars to display the total number of cars created.

Examples of how to use Python class variables

Access, mod­i­fi­ca­tion and in­her­i­tance play a key role in the safe handling of class variables in Python.

Accessing class variables

Python class variables are accessed via the class name or instance, followed by a dot and the variable name.

class MyClass:
    class_var = "This is a class variable."
# Using a class name to access a class variable
print(MyClass.class_var)  # Output: This is a class variable.
# Using an instance to access a class variable
obj = MyClass()
print(obj.class_var)  # Output: This is a class variable.
python

In Python, you can access class variables in various places:

  • In the con­struc­tor: You can call the class variable in the con­struc­tor using either the self keyword or the class name.
  • In instance methods: You can call the class variable in instance methods using either the self keyword or the class name.
  • Outside the class: You can access the class variable outside the class via the object reference or using the class name.

Modifying class variables

Python class variables can be modified directly via the class name. However, if an instance variable has the same name as a class variable and you try to change the variable via the instance, a new instance variable will be created and the class variable will remain unchanged.

class MyClass:
    class_var = "Original class variable"
obj = MyClass()
print(obj.class_var)  # Output: Original class variable
MyClass.class_var = "Modified class variable"
print(obj.class_var)  # Output: Modified class variable
python

In this example, we overwrote the class variable class_var by assigning it a new value using the class MyClass. The change is then au­to­mat­i­cal­ly adopted by the obj instance.

Class variables and in­her­i­tance

In­her­i­tance allows derived classes to access and use the class variables of the base class without having to redefine them.

class BaseClass:
    base_var = "Base variable"
class DerivedClass(BaseClass):
    pass
print(DerivedClass.base_var)  # Output: Base variable
python

Here we define a base class BaseClass, which contains the class variable base_var. The derived class DerivedClass inherits from BaseClass. Through in­her­i­tance, DerivedClass can access the class variable base_var of the base class and use it without re­defin­ing it.

Go to Main Menu