Are static class variables possible in Python?


Yes, static class variables are possible in Python. A static class variable is a variable that is shared by all instances of a class. In other words, it is a variable that belongs to the class itself, rather than to individual instances of the class.

To create a static class variable in Python, you can use the @staticmethod decorator to define a method that acts as a static class variable. Here is an example:

class MyClass:
    @staticmethod
    def my_static_var():
        return 'This is a static class variable.'

# Access the static class variable
print(MyClass.my_static_var())
This will print 'This is a static class variable.' on the console. You can also use the classmethod decorator to define a class method that can be used to set or modify the static class variable. Here is an example:
class MyClass:
    # Define a class variable
    my_static_var = 'Initial value'

    @classmethod
    def set_static_var(cls, value):
        cls.my_static_var = value

# Set the static class variable
MyClass.set_static_var('New value')

# Access the static class variable
print(MyClass.my_static_var)
This will print 'New value' on the console.

It is important to note that, in Python, class variables are not as commonly used as instance variables, which are variables that belong to individual instances of a class. In most cases, it is better to use instance variables instead of class variables.
Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.


Subscribe to be the first to know when a new Python course is released.