The staticmethod() built-in function returns a static method for a given function.
The syntax of staticmethod() is :
staticmethod(function)Using staticmethod() is considered a un-Pythonic way of creating a static function.
Hence, in newer versions of Python, you can use the @staticmethod decorator.
The syntax of @staticmethod is :
@staticmethod def func(args, ...)The staticmethod() method takes a single parameter:
function - function that needs to be converted to a static methodThe staticmethod() returns a static method for a function passed as the parameter.
Static methods, much like class methods, are methods that are bound to a class rather than its object.
They do not require a class instance creation. So, they are not dependent on the state of the object.
The classmethod() method returns a class method for the given function.
The syntax of a classmethod() method is :
classmethod(function)or more Pythonic :
@classmethod def func(cls, args, ...)the classmethod() returns a class method for the given function.
A class method is a method that is bound to a class rather its object.
It doesn’t require creation of a class instance, much like staticmethod.
No matter what , the class method is always attached to a class with first argument as the class itself cls.
When do you use class method?
Factory methods are those methods which return a class object( like constructor) for different use cases.
They can be called both by the class and its object.
Class.staticmethodFunc() or even Class().staticmethodFunc()Much more information refer to : Difference between staticmethod and classmethod
When you need a utility function that doesn’t access any properties of a class but makes sense that it belongs to the class, we use static functions.
A static method doesn’t need to access any properties of the class.
Static methods are used when we don’t want subclasses of a class change/override a specific implementation of a method.