How to create and use static class variables in Python

Overview

The variables that are defined at the class level are static variables. If we want to create a variable whose value should not be changed, we can use static variables. The static variables are accessed by using the class name, such as ClassName.static_variable_name.

Example

The below code demonstrates how to create and use static variables in Python.

class Test:
ten=10
twenty = 20
def printVal(self):
print(Test.ten)
print(Test.twenty)
print("Test.ten :", Test.ten)
print("Test.twenty :", Test.twenty)
t = Test()
print("\nt.printVal() :")
t.printVal()

Explanation

  • Line 1: We create a class, Test.
  • Lines 2 and 3: We create two static variables, ten and twenty, with values, 10 and 20, respectively.
  • Lines 4–6: We create a method, printVal . Inside this method, we print the static variables, ten and twenty.
  • Line 8 and 9: We print the static variable of the Test class.
  • Line 13–15: We create an object for the Test class. Next, we call the printVal method.

Create static variables using the constructor and instance method

The static variables can also be created inside the constructor and instance method.

class Test:
#defining static variable inside constructor
def __init__(self):
if not hasattr(Test, 'ten'):
Test.ten = 10
#defining static variable inside class method
def createTwenty(self):
if not hasattr(Test, 'twenty'):
Test.twenty = 20
try:
print("Test.ten :", Test.ten)
except AttributeError:
print("Test.ten is not defined")
t = Test()
print("\nAfter creating object for Test class")
print("Test.ten :",Test.ten);
try:
print("\nTest.twenty :", Test.twenty)
except AttributeError:
print("\nTest.twenty is not defined")
t.createTwenty();
print("\nAfter calling t.createTwenty()")
print("Test.twenty", Test.twenty);

Explanation

  • Line 1: We create a class, Test .
  • Lines 3–5: We define a class constructor that will create a static variable, ten, if the variable was not created before. We use the hasattr method to check if the static variable is already created.
  • Lines 8–10: We define a method, createTwenty, which will create a static variable, twenty, if the variable was not created before.
  • Lines 12–15: We try to access the static variable, ten of the Test class. But at this point, the static variable is not created, so we'll get an error.
  • Lines 17–19: We create a new object for the Test class. The constructor will be executed during this, and the static variable, ten, will be created. The Test.ten keyword will return 10.
  • Lines 21–24: We try to access the static variable, twenty of the Test class. But at this point, the static variable is not created, so we'll get an error.
  • Lines 26–28: We call the createTwenty method. During this, the static variable, twenty, will be created. The Test.twenty keyword will return 20.

Free Resources