Computer >> Computer tutorials >  >> Programming >> Python

What are static methods in a Python class?


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

Example

Consider the code

class OurClass:
    def method(self):
        return 'instance method called', self
     @classmethod
    def classmethod(cls):
        return 'class method called', cls
     @staticmethod
    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'