Search code examples
pythonclassstaticinstanceclass-method

Static classes in Python


I once read (I think on a page from Microsoft) that it's a good way to use static classes, when you don't NEED two or more instances of a class.

I'm writing a program in Python. Is it a bad style, if I use @classmethod for every method of a class?


Solution

  • In my experience creating a class is a very good solution for a number of reasons. One is that you wind up using the class as a 'normal' class (esp. making more than just one instance) more often than you might think. It's also a reasonable style choice to stick with classes for everthing; this can make it easier for others who read/maintain your code, esp if they are very OO - they will be comfortable with classes. As noted in other replies, it's also reasonable to just use 'bare' functions for the implementation. You may wish to start with a class and make it a singleton/Borg pattern (lots of examples if you googlefor these); it gives you the flexibility to (re)use the class to meet other needs. I would recommend against the 'static class' approach as being non-conventional and non-Pythonic, which makes it harder to read and maintain.