Table of contents
1.
Introduction
2.
What is a Static Variable in Python?
3.
How to create a Python Static Variable?
4.
How to Access Static Variables from inside a Class?
4.1.
1. Using the Class Name:
4.2.
Python
4.3.
2. Using the __class__ Attribute:
4.4.
Python
5.
How to Access Static Variables from Outside a Class?
5.1.
Python
6.
Example of Static Variable
6.1.
Python
6.2.
Python
7.
What is the Static Method?
7.1.
Using staticmethod() Method
7.1.1.
Implementation
7.2.
Python
7.3.
Using @staticmethod decorator
7.3.1.
Implementation
7.4.
Python
8.
Features of a Python Static Variable
9.
Advantages of Python Static Variable
10.
Disadvantages of Python Static Variable
11.
Frequently Asked Questions
11.1.
How do you declare a variable static in Python?
11.2.
What is the use of static in Python?
11.3.
How is the static variable declared?
11.4.
What is static variable in Python?
11.5.
Why use static in class?
11.6.
What is the difference between static class and normal class?
11.7.
Why should we use static variables?
12.
Conclusion
Last Updated: Aug 21, 2024
Medium

Static Variable in Python

Author Nitika
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Have you ever wondered how to keep track of something important across different parts of your Python program? Imagine a variable that remembers its value even when you create new objects. That's the power of static variables in Python! They're like special boxes that store information shared by everything related to a certain class, kind of like a community notice board. 

In this blog, we'll explore what static variables are and how they can be useful in your Python code, even if they don't involve the keyword "static" you might see in other programming languages. 

Python Static Variables

What is a Static Variable in Python?

In Python, a static variable, also known as a class variable, is a variable associated with a class rather than with instances of that class. It is shared among all instances of the class and is defined within the class itself, usually at the class level. Static variables are accessed using the class name or an instance of the class.

Non-static Variables are the variables associated with the objects declared within the class. They are not the same for all the objects in the given class, as compared to static variables that remain constant for the given class.
 

Must Read, Fibonacci Series in Python

How to create a Python Static Variable?

We can access Python static variables by using "className.staticVariable". A static variable can be acquired with the help of the following ways:

From inside a class: By declaring a variable within the class, but it should not be within the method, that variable will be called a static or class variable.

Using hasattr() method: This method is an incorporated operation that is used to check if the object has the static class variable constructed or not. It returns True if the object contains the static class variable constructed; otherwise, it will return False.

You can practice by yourself with the help of online python compiler for better understanding.

How to Access Static Variables from inside a Class?

Even though static variables are shared among all instances of a class, you can still access them from within the class itself. Here's how:

1. Using the Class Name:

  • Python

Python

class MyClass:
# Static variable
count = 0

def __init__(self):
# Accessing static variable using class name
MyClass.count += 1

def get_count(self):
# Accessing static variable using class name
return MyClass.count

# Creating objects
obj1 = MyClass()
obj2 = MyClass()

print(obj1.get_count())
You can also try this code with Online Python Compiler
Run Code

 

Output

2

 

Explanation:

In this example, we defined a static variable count inside the class but outside any method. In the constructor (__init__), we incremented the count using MyClass.count. This is because the count belongs to the class, not the object itself.

The get_count method also retrieves the value using MyClass.count.

2. Using the __class__ Attribute:

  • Python

Python

class MyClass:
count = 0

def __init__(self):
# Accessing static variable using __class__
self.__class__.count += 1

def get_count(self):
return self.__class__.count

obj1 = MyClass()
obj2 = MyClass()

print(obj1.get_count())
You can also try this code with Online Python Compiler
Run Code

 

Output

2

 

Explanation:

In this example, we accessed the static variable using self.__class__.count. The __class__ attribute refers to the class of the current object (similar to MyClass).

How to Access Static Variables from Outside a Class?

Static variables can also be accessed from outside the class definition. Here's how:

  • Python

Python

class MyClass:
count = 0

# Accessing static variable directly from the class name
print(MyClass.count)

# Modifying the static variable from outside (not recommended)
MyClass.count = 10
print(MyClass.count)

# Creating an object (count remains 10)
obj = MyClass()
You can also try this code with Online Python Compiler
Run Code

 

Output

0
10

 

Explanation:

In this example, we are directly accessing the static variable count using the class name MyClass.count. It's important to be cautious when modifying static variables from outside the class. This can lead to unexpected behavior if not done carefully. In most cases, it's better to use methods within the class to control modifications.

Example of Static Variable

  • Python

Python

class Vehicle:
#Class Variable

type = 'Suzuki'
def __init__(self, model, cost):

#Instance Variables

self.model = model
self.cost = cost

V1 = Vehicle('LXI', 500000)
V2 = Vehicle('VXI', 700000)


print (V1.type)
print (V2.type)

print (V1.cost)
print (V2.cost)

print (V1.model)
print (V2.model)
You can also try this code with Online Python Compiler
Run Code

 

Output

Suzuki
Suzuki
500000
700000
LXI
VXI


Let us break down the given example.

The objects which are declared in the class of 'Vehicle' enclose the type 'Suzuki'.

This includes the 'model' LXI costing 500000 INR and VXI costing 7000000 INR.

Here, 'Model' and 'Price' are known as Instance Variables that vary per object.

 

More examples to demonstrate the use of Python Static Variables
 

  • Python

Python

class CodingNinja:
staticVar = 16

print (CodingNinja.staticVar)
instance = CodingNinja()
print (instance.staticVar)

#changing the instance

instance.staticVar = 29
print (instance.staticVar)
print (CodingNinja.staticVar)
You can also try this code with Online Python Compiler
Run Code

Output

16 
16 
29
16


Let us break down the given example.

The Static Variable is declared under the class ‘CodingNinjas’. The first print command prints the answer to be 16 which has been accessed by the Instance Variable.

Further, the instance variable has been given a new value and has been printed. The last print command prints the first instance value.

Check out this article - Quicksort Python

What is the Static Method?

A static method in Python is a method associated with a class, not instances. It's defined using the @staticmethod decorator and doesn't require access to instance-specific data.

You can define a static method in Python in two ways:

  1. By using the staticmethod() method.
  2. By employing the @staticmethod decorator.

Using staticmethod() Method

Let's learn how can we use staticmethod() method to create and use a static method in Python:

Implementation

  • Python

Python

class CN:
def subtract(x, y):
return x - y
# create add static method
CN.add = staticmethod(CN.subtract)
print('The difference is:', CN.subtract(10, 2))
You can also try this code with Online Python Compiler
Run Code


Output

output

Explanation

In this example:

  • We have defined a class CN with a static method subtract that calculates the difference between two numbers.
  • Then, we created another static method add by using staticmethod and assigning it to the class CN. This essentially makes subtract accessible as static methods of the CN class.
  • Lastly we have called the subtract method.

Using @staticmethod decorator

Let's see an example of how to use the @staticmethod decorator to create and use a static method in Python:

Implementation

  • Python

Python

class CN:
@staticmethod
def subtract(x, y):
return x - y

result = CN.subtract(10, 2)
print('The difference is:', result)
You can also try this code with Online Python Compiler
Run Code


Output

output

Explanation

In this example:

  • We defined a class CN.
  • Inside the class, we have defined a static method add using the @staticmethod decorator.
  • We have called the static method directly on the class itself without creating an instance of the class.
  • The static method subtract takes two arguments and returns their difference.

Features of a Python Static Variable

  • Static variables are allocated to a memory location once the object for the class is created for the first time.
     
  • Static Variables are created outside of methods b but from within a class
     
  • Static Variables can be accessed through a class but not straight from an instance. This makes accessing and modifying the data stored in a Python Static Variable more convenient.
     
  • The behavior of a python static variable doesn’t alter for every object.
     
  • Static variables can enhance the readability of the code.
     

As you saw, the word class and object appears quite frequently above, which brings us to the question: what are classes and objects?

What is a Class?

A class is a model for creating objects having specific attributes and behaviors. It defines a set of properties and methods that the objects belonging to that class will possess.

A class is defined using 'class', which is followed by the name of the given class and a colon.

What are Objects?

Objects are class instances that hold all of the characteristics and functions defined in the class, which also includes their values. 

Let's discuss the advantages and disadvantages of Python Static Variable.

Advantages of Python Static Variable

  • Shared Data: Static variables are shared among all instances of a class, providing a common data store.
     
  • Data Integrity: Ensures consistency of data across instances.
     
  • Memory Efficiency: Shared data is stored in memory only once, saving memory.
     
  • Global Access: Easily accessible across instances and methods without instance-specific data.
     
  • Utility Functions: Useful for creating utility functions related to the class.
     
  • Improved Readability: Clearly indicates that data is shared among instances.

Disadvantages of Python Static Variable

  • Shared data can lead to unexpected changes if not managed carefully.
     
  • Easy access can lead to unintended modifications, making debugging complex.
     
  • Tightly coupling instances to shared data can reduce flexibility.
     
  • In multi-threaded programs, concurrent access can lead to race conditions and data corruption.
     
  • Testing becomes more complex when dealing with shared data.

Frequently Asked Questions

How do you declare a variable static in Python?

To declare a variable as static in Python, define it within a class but outside of any instance methods. It becomes a static variable shared among all instances of that class.

What is the use of static in Python?

In Python, the static keyword doesn't exist. Instead, you create static variables by defining them within a class but outside of any instance methods, allowing data to be shared among all instances of the class.

How is the static variable declared?

To declare a static variable in Python, you define it within a class but outside of any instance methods or constructor. It's associated with the class, not individual instances.

What is static variable in Python?

A variable shared by all instances of a class, even though Python doesn't use the "static" keyword explicitly. It's defined inside the class but outside any methods.

Why use static in class?

Static variables are useful for keeping track of class-level information that needs to be shared across all objects, like a counter or a configuration setting.

What is the difference between static class and normal class?

There's no strict "static class" in Python. However, static variables can be used to create a class that primarily serves as a collection of utility functions or constants, rather than creating individual objects.

Why should we use static variables?

Static variables maintain a single shared value across all instances of a class, ensuring consistency and efficient memory use. They enable global access within a class, control initialization, and are useful for counters, flags, or configuration settings, avoiding the need to recreate data for each object instance.

Conclusion

In this article, we learned about Static Variable in Python. These variables in Python offer a unique way to share information across all instances of a class. They act like a central storage unit for class-specific data, accessible from both inside and outside the class (with caution for external modifications).

I hope this article has helped you to understand Python Static Variables. If this article helped you in any way, then you can read more such articles on our platform, Code360.

Live masterclass