Python @staticmethod, @classmethod

While regular class methods take in the class instance as the first parameter, @classmethod and @staticmethod are available in Python to create class methods with different behavior and usage.

@staticmethod

  • does not take in the class or the instance as the implicit first parameter
  • can be called on either the class or an instance
  • cannot access class or instance properties

A typical usage might be to store any general utility function to the class, such as when the arguments have nothing to do with the class or its instances.

class Foo:
    @staticmethod
    def add(a,b):
        return a + b

Foo.add(3,12)

@classmethod

  • takes the class in as the implicit first parameter
  • can be called on either the class or an instance
  • has access to class properties

A typical usage might be to create new class instances with some alternative call signature:

class Foo:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @classmethod
    def bar(cls, a, c):
        return cls(a, c**2)

standard = Foo(2,9)
alternate = Foo.bar(2,3)