Menu Close

How to define static class variables in Python?

Sometimes, we want to define static class variables in Python.

In this article, we’ll look at how to define static class variables in Python.

How to define static class variables in Python?

To define static class variables in Python, we can add a property directly to the class.

For instance, we write:

class Test(object):
  foo = 3

Test.bar = 2
print(Test.bar)  

to define the Test.bar static variable.

We assign a value outside the class.

And we access the property value without instantiating the class.

Therefore, Test.bar should be 2, which is what is printed.

Conclusion

To define static class variables in Python, we can add a property directly to the class.

Posted in Python, Python Answers