Categories
Python Answers

How to define static class variables in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *