Home »
Python
Are static class variables possible in Python?
Python | Are static class variables possible? Here, we are going to learn about the behavior of static class variables in Python.
Submitted by Sapna Deraje Radhakrishna, on January 19, 2020
Static variables are those whose lifetime is the entire run of the application. They exist only in single instance per class and are not initiated.
The variables declared inside the class definition and not inside a method is called a class or static variables.
Example:
class TestClass:
static_variable = 2
The variable static_variable is accessed as follows,
TestClass.static_variable
Output
class TestClass:
#creates a class level variable
static_variable = 2
print(TestClass.static_variable)
TestClass.static_variable = 5
print(TestClass.static_variable)
But the above-created static_variable is distinct from any instance-level static_variable, so we could have the below also.
test_obj = TestClass()
test_obj.static_variable = 6
print(TestClass.static_variable, test_obj.static_variable)
ADVERTISEMENT
ADVERTISEMENT