Last week we had a nice conversation during a python code review about when class and static methods should be used, or either they should not be used at all.
Find below my opinions around this topic, feel free to comment and bring some discussion .
In general, you should think about moving a class or static method to the module that holds the class definition. As you may well know, functions are first class citizens in python:
This snippet can be refactored to:
Some exception that might apply:
The class provides several staticmethod to validate attributes, retrieve class information, etc. Moving all these methods might fill up the module with too many definitions that are clearly tight to a specific class.
The module holds several classes
You want to define an auxiliar method to create an instance, and you want the childs to be able to override the initialization (think if you should use composition instead of inheritance!):
The output of the program is:
Bar includes an additional attribute to the instance, but the preliminar instance initilization is similar to what Foo does.
There are other alternatives to the class method in this case though:
defining a factory class to return the proper class.
define a function that receives as parameter a function to be applied while defining the instance: