Python class variables (class variables in English) represent a structured way of sharing data between different instances of a class. Additionally, changes to a class variable are reflected in all instances of the class. Thus, they do not need to be redefined at each instantiation.
Python class variables: what are they?
In Python, class variables are created within a class. Unlike instance variables, which are specific to each instance of a class, class variables keep the same value for all instances. These variables are usually defined before the constructor and are accessible to all instances of the class.
Python class variables are often used to store information common to all instances of a classsuch as configuration values, default values, or common states in a class hierarchy. Additionally, class variables can be used to define methods or class attributes that are shared by all instances of a class, improving functionality and code organization.
Web hosting with personal advisor!
Powerful, flexible and high-performance web hosting with email box, personal advisor and domain included 1time year !
Domain
SSL Certificate
24/7 Support
Python class variables: syntax
Python class variables are created inside 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
python
Inside the classroom Car
we define the class variable total_cars
to track the total number of cars. The manufacturer __init__
is called when a new instance of the class is created. At each instantiation, the instance variables brand
And model
are defined and the class variable total_cars
is increased by 1.
By calling the method display_details()
we display the details of each car instance. In a f-Stringa Python string formatting method; we access the class variable total_cars
to display the total number of cars created.
Examples of using Python class variables
For safe use of class variables in Python, it is mainly access, modification and inheritance that play a role.
Accessing class variables
Access to Python class variables is done by the name of the class or instancefollowed by a period and the name of the variable.
class MyClass:
class_var = "This is a class variable"
# using class name to access class variable
print(MyClass.class_var) # Output: This is a class variable
# using instance to access class variable
obj = MyClass()
print(obj.class_var) # Output: This is a class variable
python
In Python, class variables can be retrieved from different places:
-
In the constructor : the class variable can be called inside the constructor, either by the keyword
self
either by the name of the class. -
In instance methods : the class variable can be called inside instance methods either by the keyword
self
either by the name of the class. - Outside the classroom : outside the class, the class variable can be accessed either by the object reference or by the class name.
Modify class variables
Python class variables can be modified directly by the class name. If an instance variable has the same name as a class variable and you try to modify 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 replace the class variable class_var
by assigning it a new value via the class MyClass
. The modification is automatically taken into account by the instance obj
.
Class Variables and Inheritance
Through inheritance, derived classes can access class variables of the base class and use them 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
. Thanks to the inheritance, DerivedClass
can access the class variable base_var
from the base class and use it without having to redefine it.