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
@classmethod def from_json(cls, data): return cls(**json.loads(data))correctly builds the right subclass if called as
Subclass.from_json(...), because `cls` is whichever class the method was actually called on.