Open In App

Class or Static Variables in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

All objects share class or static variables. An instance or non-static variables are different for different objects (every object has a copy). For example, let a Computer Science Student be represented by a class CSStudent. The class may have a static variable whose value is “cse” for all objects. And class may also have non-static members like name and roll.

 In C++ and Java, we can use static keywords to make a variable a class variable. The variables which don’t have a preceding static keyword are instance variables. See this for the Java example and this for the C++ example.

Explanation:

In Python, a static variable is a variable that is shared among all instances of a class, rather than being unique to each instance. It is also sometimes referred to as a class variable, because it belongs to the class itself rather than any particular instance of the class.

Static variables are defined inside the class definition, but outside of any method definitions. They are typically initialized with a value, just like an instance variable, but they can be accessed and modified through the class itself, rather than through an instance.

Features of Static Variables

  • Static variables are allocated memory once when the object for the class is created for the first time.
  • Static variables are created outside of methods but inside a class
  • Static variables can be accessed through a class but not directly with an instance.
  • Static variables behavior doesn’t change for every object.

The Python approach is simple; it doesn’t require a static keyword. 

Note: All variables which are assigned a value in the class declaration are class variables. And variables that are assigned values inside methods are instance variables.

Example:

Python




# Python program to show that the variables with a value
# assigned in class declaration, are class variables
 
# Class for Computer Science Student
class CSStudent:
    stream = 'cse'                  # Class Variable
    def __init__(self,name,roll):
        self.name = name            # Instance Variable
        self.roll = roll            # Instance Variable
 
# Objects of CSStudent class
a = CSStudent('Geek', 1)
b = CSStudent('Nerd', 2)
 
print(a.stream)  # prints "cse"
print(b.stream)  # prints "cse"
print(a.name)    # prints "Geek"
print(b.name)    # prints "Nerd"
print(a.roll)    # prints "1"
print(b.roll)    # prints "2"
 
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"
 
# Now if we change the stream for just a it won't be changed for b
a.stream = 'ece'
print(a.stream) # prints 'ece'
print(b.stream) # prints 'cse'
 
# To change the stream for all instances of the class we can change it
# directly from the class
CSStudent.stream = 'mech'
 
print(a.stream) # prints 'ece'
print(b.stream) # prints 'mech'


Output

cse
cse
Geek
Nerd
1
2
cse
ece
cse
ece
mech

Output: 

cse
cse
Geek
Nerd
1
2
cse
ece
cse
ece
mech

Example:

Python




class MyClass:
    static_var = 0
 
    def __init__(self):
        MyClass.static_var += 1
        self.instance_var = MyClass.static_var
 
obj1 = MyClass()
print(obj1.instance_var)  # Output: 1
 
obj2 = MyClass()
print(obj2.instance_var)  # Output: 2
 
print(MyClass.static_var)  # Output: 2


Output

1
2
2

Explanation:

in this example, we define a class MyClass that has a static variable static_var initialized to 0. We also define an instance variable instance_var that is unique to each instance of the class.

When we create an instance of the class (obj1), we increment the value of the static variable by 1 and assign it to the instance variable. When we create another instance of the class (obj2), we increment the static variable again and assign the new value to the instance variable for that instance.

Finally, we print out the value of the static variable using the class itself, rather than an instance of the class. As you can see, the value of the static variable is shared among all instances of the class, and it is incremented each time a new instance is created.

Static variables can be useful for maintaining state across all instances of a class, or for sharing data among all instances of a class. However, it’s important to use them carefully and to ensure that their values are synchronized with the state of the program, especially in a multithreaded environment.

Advantages:

  • Memory efficiency: Since static variables are shared among all instances of a class, they can save memory by avoiding the need to create multiple copies of the same data.
  • Shared state: Static variables can provide a way to maintain shared state across all instances of a class, allowing all instances to access and modify the same data.
  • Easy to access: Static variables can be accessed using the class name itself, without needing an instance of the class. This can make it more convenient to access and modify the data stored in a static variable.
  • Initialization: Static variables can be initialized when the class is defined, making it easy to ensure that the variable has a valid starting value.
  • Readability: Static variables can improve the readability of the code, as they clearly indicate that the data stored in the variable is shared among all instances of the class.

Disadvantages:

  • Inflexibility: Static variables can be inflexible, as their values are shared across all instances of the class, making it difficult to have different values for different instances.
  • Hidden dependencies: Static variables can create hidden dependencies between different parts of the code, making it difficult to understand and modify the code.
  • Thread safety: Static variables can be problematic in a multithreaded environment, as they can introduce race conditions and synchronization issues if not properly synchronized.
  • Namespace pollution: Static variables can add to the namespace of the class, potentially causing name conflicts and making it harder to maintain the code.
  • Testing: Static variables can make it more difficult to write effective unit tests, as the state of the static variable may affect the behavior of the class and its methods.

Overall, static variables can be a useful tool in Python programming, but they should be used with care and attention to potential downsides, such as inflexibility, hidden dependencies, and thread safety concerns.



Last Updated : 28 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads