Skip to main content

How to Create Static Variables in Python

In Python, a static variable is a variable that is declared inside a class, but not inside a function. This means that it can only be accessed via the class in which it is declared. Static variables a.ka.a class variable doesn’t affect the state of an object.

Static variables can be created using the staticmethod() or the @staticmethod decorator. The staticmethod() method is used to create static variables that are accessible only through the class in which they are declared. The @staticmethod decorator is used to create static variables that are accessible through both the class and the instance of the class.

Creating static variables using the staticmethod() method is simple. All you need to do is wrap the staticmethod() to a function definition. This function can then be used to access the static variable.

class Student:
    def showAge(birthdate):
        print(birthdate)
Student.showAge = staticmethod(Student.showAge)
Student.showAge("1980-01-01")

Creating static variables using the @staticmethod decorator is more simple. You only need to add the @staticmethod decorator to a function defined inside a class. This function can then be used to access the static variable.

class Student:
    @staticmethod
    def showAge(birthdate):
        print(birthdate)

Student.showAge("2000-05-26")

Static variables are useful for storing data that does not need to be associated with a particular instance of a class. For example, you might want to store a list of all the objects that have been created from a particular class. This list would be a static variable because it would not need to be associated with any particular object.

Static variables can also be used to create singletons. A singleton is an object that can only be instantiated once. Singletons are useful for storing data that needs to be shared between multiple instances of a class.

By continuing to use the site, you agree to the use of cookies.