What are static methods in a Python class?

PythonServer Side ProgrammingProgramming

Any python class has three types of methods like the instance methods, class methods and the static methods.


Consider the code

class OurClass:
    def method(self):
        return 'instance method called', self
    def classmethod(cls):
        return 'class method called', cls
    def staticmethod():
        return 'static method called'

The third method, OurClass.staticmethod was marked with a @staticmethod decorator to flag it as a static method.

This type of method takes neither a self nor a cls parameter but it can accept an arbitrary number of other parameters.

Therefore a static method can neither modify object state nor class state. Static methods are restricted in what data they can access - and they’re primarily a way to namespace your methods. We can call the staticmethod from above code as follows 

>>> obj = OurClass()
>>> obj.staticmethod()
'static method called'

Published on 24-Jan-2018 13:14:02