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=10twenty = 20def 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,
tenandtwenty, with values,10and20, respectively. - Lines 4–6: We create a method,
printVal. Inside this method, we print the static variables,tenandtwenty. - Line 8 and 9: We print the static variable of the
Testclass. - Line 13–15: We create an object for the
Testclass. Next, we call theprintValmethod.
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 constructordef __init__(self):if not hasattr(Test, 'ten'):Test.ten = 10#defining static variable inside class methoddef createTwenty(self):if not hasattr(Test, 'twenty'):Test.twenty = 20try: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 thehasattrmethod 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,
tenof theTestclass. 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
Testclass. The constructor will be executed during this, and the static variable,ten, will be created. TheTest.tenkeyword will return10. - Lines 21–24: We try to access the static variable,
twentyof theTestclass. But at this point, the static variable is not created, so we'll get an error. - Lines 26–28: We call the
createTwentymethod. During this, the static variable,twenty, will be created. TheTest.twentykeyword will return20.