How to create and use Python class variables
Python class variables are a structured 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 instantiated.
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 constructor 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 configuration settings, default values or shared states across a class hierarchy. Class variables also allow you to define class methods or attributes that every instance can access, enhancing both the functionality and the structure of your code.
- 99.9% uptime and super-fast loading
- Advanced security features
- Domain and email included
What is the syntax of Python class variables?
Python class variables are created within the class definition 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}")
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
pythonWithin the class Car
we define the class variable total_cars
to keep track of the total number of cars. The constructor __init__
is called when a new instance of the class is created. At each instantiation, the instance variables brand
and model
are set and the class variable total_cars
is incremented by 1.
By calling the display_details()
method, we can display the details of the respective 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, modification and inheritance 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.
pythonIn Python, you can access class variables in various places:
-
In the constructor: You can call the class variable in the constructor 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
pythonIn this example, we overwrote the class variable class_var
by assigning it a new value using the class MyClass
. The change is then automatically adopted by the obj
instance.
Class variables and inheritance
Inheritance 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
pythonHere we define a base class BaseClass
, which contains the class variable base_var
. The derived class DerivedClass
inherits from BaseClass
. Through inheritance, DerivedClass
can access the class variable base_var
of the base class and use it without redefining it.