Class or Static Variables in Python

Class or Static Variables in Python

The static variables are useful when you want to store data that is shared across multiple objects of a class. This helps in accessing the shared data using the class name, which is common for all the instances. In this blog, you will learn in detail about static variables in Python.

Table of Contents:

Static Variables in Python

Static variables are like shared pieces of information that all instances of a class can access. Suppose all the objects of a class were like students in a classroom, and if they all shared one common book, then every student could read the same information in that book without having their copy.

Features of the Static Variable in Python

  1. Memory Efficient: The static variables occupy memory when the class is loaded, and the value remains shared across all instances.
  2. Access Through Class: Static variables can be accessed using the class name, and these class names are common to all the instances of the class.
  3. Consistent Behavior: The value of a static variable remains constant for all instances, so there is uniform behavior.
  4. Shared State: Static variables are shared among all instances. They can be used to keep a common state or configuration for the class.
  5. Inheritance: Static variables are inherited by the subclasses. It allows the sharing of attributes among classes.

Methods to Create and Use Static Variables in Python

Below are a few methods to create and use static variables in Python:

Method 1: Using a Class Variable as a Static Variable in Python

Static variables are created for the class variables, not for the instance variables. You can declare a static variable outside any method but inside the class. The static variables are shared in all instances.

Example:

Python

Output:

Using a Class Variable as a Static Variable in Python

Explanation: The static_variable is shared by both obj1 and obj2, and there is just one copy of the static_variable for the entire class. Each time you create an object, the static variable is updated.

Method 2: Creating Static Variables Using a Static Method in Python

Static methods do not require access to instance data (self). They are used when you want to perform some tasks that do not belong to a specific object, like utility functions. You can define a static method by using the @staticmethod decorator.

Example:

Python

Output:

Explanation: The class can be called directly using @staticmethod decorator. There is no need for instance-specific data. Here the static variable is updated by 1.

How to Access Static Variables in Python 

Python static variables are shared classes among all instances. They can be accessed by different methods. 

Method 1: Using Object method(accessing via an instance) in Python

The static method accesses the variable by an instance. The static method declares a variable with an instance (object).

Example:

Python

Output:

Explanation: Here the static variable is being accessed with the help of an instance. This is the general access of variables. It won’t modify the value or variable in it.

If you want to modify the variables inside the static you can use this code, 

Example:

Python

Output:

Explanation: Now, this code modifies the variable inside the static from 20 to 50. Modifying static variables via class is preferable to using instance because if we modify using instance it will create an instance variable not modifying the actual static variable.

Method 2: Using a Function inside a Class in Python

Static variables can also be accessed inside a function but it will retain their values without any changes. 

Example:

Python

Output:

Explanation: The static variable inside a function will remember its values across multiple calls which helps in tracking shared data like logs, and counters.

Alternative Method to Access Variables: Using @classmethod in Python

The @classmethod is an alternative method in Python that helps in accessing static variables. It ensures that the class attributes are accessible consistently. 

Example:

Python

Output:

Explanation: The @clssmethod works well with inheritance. This method will be helpful in modifying static variables across all instances.

When to Use Static Variables in Python

Static variables should be used when shared data is required across all instances of a class. They serve to save space and enforce uniformity. Some of the key situations where static variables are useful:

  1. Shared Data: These would be data for all objects of a class that touch the same value, usually a counter-keeping track of instances or something similar.  
  2. Memory Efficiency: This prevents storage duplication by allowing you to store information in class space rather than instance space. 
  3. Constant Values: The storing of static data for things that do not change such as tax rates, default configurations, or environment settings. 
  4. Tracking Global State: Maintaining a common state for all instances, e.g., total users in an application. 
  5. Call Static Methods: When the utility functions that need to be invoked do not rely on instance-specific data. 

Best Practices for Static Variables in Python

Static variables help to store the data efficiently in Python. Using them correctly ensures better memory usage and also avoids unnecessary object creation. Here are some best practices to follow while working with static variables.

  • Shared Data: Use static variables if the value is the same for all class instances.
  • Access using Class Name: Access static variables using the class name instead of self to avoid confusion.
  • Frequency change: Static variables should contain data that does not change often and helps to keep it basic.
  • Used in large programs: It becomes very useful in reducing the amount of memory a program uses because many objects share the same data.

Comparing Static Variables and Static Methods

FeaturesStatic VariablesStatic Methods
PurposeUsed to store the shared dataUsed to perform utility operations
AccessIt can be accessed using the class name with the variable as suffix ClassName.variableIt can be accessed using the class name with method() as suffix ClassName.method()
Use of InstanceValues are the same for all the instances of the ClassNo instance is needed to call the method 
ModificationThe class can be modified, but it affects all the instancesThe class cannot be modified
BindingBound to class shared by all the instances.Not bound to any instance or class, it works independently
Use CaseMainly used for storing the shared data for all the objects of the classUsed for utility functions that do not require any class or instance data

Real-world Examples of Static Variables

Example 1: Tracking the Number of Users in an Application

When we need to track the number of users in an application we can use static variables to count all the registered users. 

Python

Output:

Explanation: The static method fetched the count of people who registered in the application.

Example 2: To generate Unique Order IDs for an E-Commerce Platform

The static variable order_counter ensures each order gets a unique ID. Since it’s a class variable, all instances share the same counter, preventing duplicate order numbers.

Python

Output:

Explanation: The static method fetched the details of the E-Commerce customers with their unique order ID.

Example 3: Logging System for an Application

To check the logs we need to retrieve the data for that we can use a static method with a static variable.

Python

Output:

Explanation: The logs static variable stores all log messages. The static method add_log() adds messages to the log list, and show_logs() retrieves them. 

Conclusion

Static variables in Python are an easy and secure way to share information. A static variable is shared by all objects of a class. It stores common data in one place which helps in avoiding duplicate copies and saves memory. Understanding static variables thoroughly helps you to share resources between classes, which helps to avoid repeating the operations.

FAQs

1. What is a static variable in Python?

A static variable is a class-level variable that remains constant for all objects of the class.

2. How do you access a static variable?

You can access a static variable by using the class name, such as ClassName.variable_name.

3. What is a static method in Python?

A static method is a function within a class that doesn’t consist of instance-specific information and can be accessed using the class name.

4. How do I declare a static method?

You can declare a static method with the @staticmethod decorator before a function within a class.

5. When should I apply static variables and static methods?

Static variables can be applied to the shared information and static methods are applied to the utility functions that don’t require data related to the instance.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner