Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Object-oriented PythonMiddleVery commonTheory

What is the difference between an instance method, a `@classmethod` and a `@staticmethod`?

Answer

An instance method automatically receives the instance as its first argument (`self`) and can read or modify that instance's state. A `@classmethod` automatically receives the class itself as its first argument (`cls`) instead of an instance, which makes it useful for alternative constructors that need to know the exact class, including a subclass, without hardcoding the class name. A `@staticmethod` receives neither `self` nor `cls`; it behaves like a plain function that is only namespaced inside the class for organizational purposes, with no automatic access to instance or class state.

Strong answer includes

  • instance method receives self and can touch instance state
  • classmethod receives cls, common for alternative constructors
  • staticmethod receives neither, just namespaced inside the class

Practical example

Python example
@classmethod def from_json(cls, data): return cls(**json.loads(data))

correctly builds the right subclass if called as

Python example
Subclass.from_json(...)

, because `cls` is whichever class the method was actually called on.

#oop#classmethod#staticmethod

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsData modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols