Static Variable in Python | Class Variable, Example

When we define a variable inside a class definition, but outside any of class’s method definitions, it is called static variable in Python.

In other words, a variable that is mutually shared by all the instances (objects) of a class is called static variable. It is also called class variable or class attribute in Python because it belongs to a class itself rather than any specific instance of the class.

Static or class variables are specific to the class. All instances share static variables. Unlike instance variables, which have unique values for each object, static variables shares the same value among all objects of a particular class.

This feature is especially useful for scenarios where we want to share a value among multiple instances (objects) of the same class. However, we do not use static variables as frequently as

Defining a Static Variable or Class Variable in Python


In Python, we can define a static variable within the class definition, but outside any method definitions defined in the class. Let’s consider a simple example:

class Circle:
  # Class definition.
    pi = 3.14159 # Declaration of class variable.

In this example, we have defined a class by using the keyword class with class_name. The pi variable is a static variable within the Circle class. All instances of the class Circle will share the same value of static variable pi, as shown in the below figure. .

Static variable in Python

In C++ and Java, we use static keywords to define a static variable or class variable. If we define a variable without a static keyword, it is considered as an instance variable. But in Python, we declare a static variable without any static keyword.

Accessing a Static Variable


Accessing a static variable is simple and straightforward. We can directly call and access it using the class name with dot (.) operator, but not through the instance of a class. The general syntax to call and access the static variable is as:

class_name.variable_name

In the above syntax, class_name is the name of class and variable_name is the name of class variable or class attribute. For example:

print(Circle.pi)  # Output: 3.14159

Let’s take some important example programs based on the declaration of static variables in Python.

Example 1:

# Python program to define and access a class variable.
# Create a class MyClass.
class MyClass:
  # Class definition.
    class_variable = "I am a class variable"  # Class variable declaration.

# Outside the class definition.
# Calling class variable.
print(MyClass.class_variable)
Output:
       I am a class variable

In this example, we have defined a class using the keyword class with class name. Then, we have declared a class variable with a string value. Outside the class definition, we have accessed class variable and printed its value on the console.

Features of Static Variables in Python


There are some key features of static variable definition in Python that you should keep in mind. They are:

  • Static variables are allocated memory once, when an instance for the class is constructed for the first time.
  • We construct static variables outside of method definitions but inside a class definition.
  • We can call and access them through a class name, but not directly with an object.
  • The behavior of static variables doesn’t change for every instance.

Please note that a variable which is assigned a value in the class declaration is a class variable. And the variable that is assigned a value inside method definition is an instance variable.

Python Class Variables in Different Scopes


Class variables are accessible within the class and we can also use within class methods. However, they are not directly accessible within instance methods. To access them, we need to use the class name. Look at the below different example code.

Example 2:

# Python program to access a class variable inside the instance method.
# Create a class MyClass.
class MyClass:
  # Class definition.
    class_variable = "I am a static variable"  # Class variable declaration.

  # Instance method declaration.
    def access_class_var(self):
        print(MyClass.class_variable) # Accessing class variable inside the instance method.

# Outside the class definition.
# Create an object of class MyClass.
obj = MyClass()

# Call the instance method using the object reference variable obj.
obj.access_class_var()
Output:
      I am a static variable

Example 3:

# Python program to access a class variable inside the instance and class methods.
# Create a class MyClass.
class MyClass:
  # Class definition.
    static_var = "I am a static variable"  # Class variable declaration.

  # Instance method declaration.
    def access_static_var(self):
        print(MyClass.static_var) # Accessing class variable inside an instance method.

  # Declare a class method.
    @classmethod
    def access_class_var(cls):
        print(MyClass.static_var) # Accessing static variable inside a class method.

# Outside the class definition.
# Create an object of class MyClass.
obj = MyClass()

# Call the instance method using the object reference variable obj.
obj.access_class_var()

# Call the class method using class name.
MyClass.access_class_var()
Output:
       I am a static variable
       I am a static variable

Modifying Static Variables in Python


The value of static variable is shared among all the instances of a class, but we can also modify its value using the class name. However, be cautious when modifying static variables, as the change will affect all instances of a class.


In other words, if we modify the value of class variable at runtime, Python dynamically changes the value of class variable to value in all existing class instances. Let’s take an example based on it.

Example 4:

# Python program to modify the value of static variable at run time.
class BankAccount:
    interest_rate = 0.06  # Static variable representing the interest rate

    def __init__(self, balance):
        self.balance = balance

    def apply_interest(self):
        self.balance += self.balance * BankAccount.interest_rate


# Create two bank account instances
account1 = BankAccount(1000)
account2 = BankAccount(1500)

# Print initial balances
print("Initial balance for account1:", account1.balance)
print("Initial balance for account2:", account2.balance)

# Modify the static interest_rate using the class name
BankAccount.interest_rate = 0.07

# Apply interest to both accounts
account1.apply_interest()
account2.apply_interest()

# Print balances after applying interest
print("Balance for account1 after interest:", account1.balance)
print("Balance for account2 after interest:", account2.balance)
Output:
       Initial balance for account1: 1000
       Initial balance for account2: 1500
       Balance for account1 after interest: 1060.0
       Balance for account2 after interest: 1590.0

In this example, we have defined a BankAccount class representing bank accounts. Inside the class, we have defined a static variable interest_rate that represents the interest rate applicable to all bank accounts.

Then, we have created two objects of the BankAccount class (account1 and account2) with initial balances (i.e. argument values). The apply_interest() method applies interest to the account balance by multiplying it with the static interest_rate.

After creating the objects, we have printed their initial balances on the console. Then, we have modified the static interest_rate using the class name as (BankAccount.interest_rate). This change affects all objects of the class.

Finally, we have applied the interest to both accounts again and print their balances after applying the interest. The output shows that the modified interest_rate affected both accounts, resulting in updated balances.

Counting Function Calls using Class Variable in Python


Let’s consider a scenario where we will count how many times a function is called. We can achieve this using a static variable, as explained in the below example code.

Example 5:

# Python program to count the function call.
class Counter:
    count = 0 # class variable declaration.

    @classmethod
    def increment_count(cls):
        Counter.count += 1

    @classmethod
    def get_count(cls):
        return Counter.count


Counter.increment_count()
Counter.increment_count()
Counter.increment_count()
print(Counter.get_count()) 
Output:
       3

In this code example, we have defined a Counter class that contains a static variable count set to 0 initially. We will use this variable to keep track of the count. Then, we have defined two static methods within the class: increment_count() and get_count().

The static method increment_count() increments the value of the static variable count by 1 each time it’s called. This method doesn’t take any parameters because it operates solely on the static variable. The static method get_count() simply returns the value of the static variable count.

We have called the increment_count() method thrice using the class name Counter. This increases the value of the static variable count by 3, making it 3. Finally, we have called the get_count() method using the class name, that will return the value of the static variable count and print on the console. The output is 3, as expected.

As you observe in this example code, the static variable count is shared among all instances of the Counter class and is updated by the static method increment_count. The static method get_count() allows us to retrieve the value of the static variable.

Counting Instances with Static Variables in Python


In Python, we can also use static variables to count the number of instances created from a class. It can be useful when we want to monitor on the object creation. Let’s take a simple example based on it.

Example 6:

# Python program to count the object creation.
class InstanceTracker:
    instances = [] # An empty static list to store instances of the class

    def __init__(self):
      # Appending each instance to the list
        InstanceTracker.instances.append(self)

    @staticmethod
    def get_instance_count():
      # Returning the count of instances in the list
        return len(InstanceTracker.instances)

# Creating an instance of the InstanceTracker class
obj1 = InstanceTracker()
obj2 = InstanceTracker() # Creating another instance
obj3 = InstanceTracker() # Creating a third instance

# Printing the total count of instances
print(InstanceTracker.get_instance_count()) 
Output:
       3

In this example code, we have defined a class InstanceTracker that contains an empty static variable named instances. This static variable will store references of instances of the class. In other words, it will keep the track of the number of instances created from the class.

Inside the class, we have defined __init__() method (constructor) that gets executed whenever an instance of the class is created. The statement InstanceTracker.instances.append(self) appends the current instance to the instances list.

Then, we have defined a static method get_instance_count(). This method does not take any arguments. It simply returns the length of the instances list, which represents the count of instances created.

We have created three instances (obj1, obj2, and obj3) of the InstanceTracker class. After creating the instances, the static method get_instance_count() is called using the class name InstanceTracker. This method retrieves the count of instances by checking the length of the instances list.

Each time an object is constructed, its reference is added to the static variable instances. The get_instance_count() method then returns the count of objects by determining the length of this list.

Realtime Use of Static Variable in Python


Imagine an owner of the car showroom asks you to add a feature to your program. He wants to keep a count of cars in the showroom at any given time. To accomplish the request, you can add another variable called car_count to the Car class.

Each time the dealer receives a new car, car_count is incremented by 1. Each time the dealer sells the car, the car_count is decremented by 1.

How will you modify the program code to add the car-counting feature? Storing the same value in each Car object takes up unnecessary memory space, especially when the number of Car objects increases.

When the dealership receives or sells the car, you also need to update the value of every Car object. You may need too many resources to store the copies of the same thing when it needs constant updating.

In this scenario, you can use static variables to save resources and simplify the program code. Let’s take a simple example program based on this scenario.

Example 7:

class Car:
    total_cars = 0  # Static variable to track total cars in inventory
    car_count = 0  # Static variable to track cars in the showroom

    def __init__(self, make, model):
        self.make = make
        self.model = model
        Car.total_cars += 1
        Car.car_count += 1  # Increment car_count for each new car received

    def sell_car(self):
        if Car.car_count > 0:
            Car.car_count -= 1  # Decrement car_count when a car is sold
            print(f"Sold: {self.make} {self.model}")
        else:
            print("No cars to sell.")

    def display_info(self):
        print(f"Make: {self.make}, Model: {self.model}")


# Creating car instances
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")
car3 = Car("Ford", "Mustang")

# Displaying car information
car1.display_info()  
car2.display_info()  
car3.display_info()

# Selling cars and updating car_count
car1.sell_car()  
car2.sell_car()  

# Printing total number of cars and cars in showroom using the static variables
print("Total cars in inventory:", Car.total_cars)  
print("Cars in showroom:", Car.car_count) 
Output:
      Make: Toyota, Model: Camry
      Make: Honda, Model: Civic
      Make: Ford, Model: Mustang
      Sold: Toyota Camry
      Sold: Honda Civic
      Total cars in inventory: 3
      Cars in showroom: 1

In this example code, we have defined a Car class that contains two static variables named total_cars and car_count. The static variable total_cars will keep the track of total cars in inventory.

The car_count static variable will keep the track of the number of cars currently in the showroom. The __init__() constructor method increments both total_cars and car_count when a new car is added to the inventory.

The sell_car() method checks if there are cars available in the showroom (car_count > 0). If so, it decrements car_count and prints a message indicating the sold. If no cars are available, it prints a message stating there are no cars to sell. The display_info() method remains the same and displays the make and model information of each car.

After creating instances, we have called display_info() method to display the car information. Then, we have called sell_car() method.

Finally, the program displays the total number of cars in the inventory (Car.total_cars) and the number of cars in the showroom (Car.car_count). This program accomplishes the request of owner by maintaining a count of cars in the showroom and updating the count when cars are added or sold.

Simulating Global Constants with Class Variable


In some cases, where we need constants that are specific to a class, static variables serve as efficient alternatives to global constants. In simple words, we can use class variables with immutable values as default for instance variables.

Example 8:

class Constants:
    GRAVITY = 9.81
    SPEED_OF_LIGHT = 299792458

print(Constants.GRAVITY)        
print(Constants.SPEED_OF_LIGHT) 
Output:
       9.81
       299792458

Advantage of Static Variables in Python


There are several advantages of using the static variables in Python because they optimize the memory efficiency, code readability, and maintainability. The key advantages of using static variables are as follows:

(1) Memory Efficiency: Since all the instances of a class share the same copy of static variables, therefore, they save memory by avoiding the unnecessary creation of multiple copies of the same data.

(2) Shared Data: Static variables can provide a way to maintain common data across all instances of a class, allowing multiple instances to access and modify the same data.

(3) Easy Access: We can easily access the static variables using the class name itself, without creating an object of the class. This helps to understand the variable is associated with the class rather than any specific instance. This improves the code readability.

(4) Initialization: We can initialize the static variable at the time of defining a class, making it easy to ensure that the variable has a valid starting value.

(5) Readability: Static variables can improve the readability of the code, as they clearly tell that the data stored in the variable will share among all objects of the class.

(6) Efficient Resource Management: We can also use static variables to track and manage resources that need to be shared among instances, such as database connections, file handles, or network sockets.

(7) Consistency Across Instances: Class variables maintain consistent values across all instances. Any changes made to a static variable are reflected in all instances.

Disadvantages of Static Variables


In addition to advantages of static variables, there are some disadvantages of using static variables in Python:

(1) Inflexibility: Static variables can be inflexible when we need to share different values for different instances. This is because their values are shared across all instances of the class.

(2) Thread safety: If the program involves multi-threading or multiprocessing, modifying static variables can lead to synchronization issues if not properly synchronized. Without proper synchronization, concurrent access to static variables can result in unpredictable behavior and bugs.

(3) Obscured Dependencies: Static variable can create hidden dependencies between different parts of the code, making it less clear that a change to a static variable affect which parts of the program are affected.

(4) Code Maintainability: As the number of static variables increases within a class, the code might become less maintainable.

(5) Difficulty in Debugging: When unexpected behavior occurs due to any change in a static variable, tracing the source of the issue can be more complex. Understanding the execution flow and identifying the point of modification can be challenging.


In this tutorial, we have explained the static or class variable in Python with the help of various examples. Hope that you will have understood the basic features of using class variables and practiced all example programs.
Thanks for reading!!!

Please share your love