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.
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()
Test.ten and twenty, with values, 10 and 20, respectively.printVal . Inside this method, we print the static variables, ten and twenty.Test class.Test class. Next, we call the printVal 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);
Test . ten, if the variable was not created before. We use the hasattr method to check if the static variable is already created.createTwenty, which will create a static variable, twenty, if the variable was not created before. ten of the Test class. But at this point, the static variable is not created, so we'll get an error. Test class. The constructor will be executed during this, and the static variable, ten, will be created. The Test.ten keyword will return 10.twenty of the Test class. But at this point, the static variable is not created, so we'll get an error. createTwenty method. During this, the static variable, twenty, will be created. The Test.twenty keyword will return 20.