classmethodmust have a reference to a class object as the first parameter, whereas
staticmethodcan have no parameters at all.
classmethodare for when you need to have methods that aren’t specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses. Factory methods (alternative constructors) are indeed a classic example of class methods.
If you have a class MyClass, and a module-level function that operates on
MyClass(factory, dependency injection stub, etc), make it a
Here is some code example:
Pay attention to
cls parameter in the example above;
cls is an object that holds
class itself, not an instance of the class. It’s pretty cool because if we inherit our
Date class, all children will have from_string defined also.
staticmethoddoesn’t have any access to what the class is- it’s basically just a function, called syntactically like a method, but without access to the object and it’s internals (fields and another methods), while
staticmethod is similar to C++ or Java’s static methods, which can be called
without creating an instance of a class.