In Python, a method that can be defined on a class are static methods.

Static methods are defined within a class but are not tied to either the class nor any instance of the class; they do not receive the special first parameter representing either the class (cls for class methods) or the instances (self for instance methods).

They are in effect, the same as free standing functions but are defined within a class often for convenience or to provide a way to group such functions together.

Static methods in Python is a method that is decorated with the @staticmethod decorator.

static method in python

A static method does not receive an implicit first argument. To declare a static method, use this idiom as per the Python documentation:

class C: 
     @staticmethod 
     def f(arg1, arg2, ...): ...

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()).

An example of static method is given below,

class Account:
    """ An example class to hold a Account detail"""
    instance_count = 0

    @classmethod
    def increment_instance_count(cls):
        cls.instance_count += 1

    @staticmethod
    def static_function():
        print('Static method')

    def __init__(self, number):
        Account.increment_instance_count()
        self.number = number

Static methods in Python are invoked via the name of the class or using the instance of the class they are defined in, for example:

>>> Account.static_function()
Static method
>>> acct1 = Account()
>>> acct1.static_function()
Static method

Even though both Accounnt.static_function() and acct1.static_function() are valid calls, the static method receives reference of neither. Hence it doesn’t have any arguments – neither self nor cls.

Conclusion

In this article, we saw about,

  • What is static method in python?
  • @staticmethod decorator
  • How static methods can be invoked for use in program.

Reference

https://docs.python.org/3/library/functions.html#staticmethod