What's the difference between an instance method, a classmethod, and a staticmethod?
Quick Answer
An instance method takes self and operates on a specific instance. A classmethod (@classmethod) takes cls instead of self and operates on the class itself, commonly used for alternative constructors. A staticmethod (@staticmethod) takes neither. It's just a regular function namespaced inside the class for organizational purposes, with no automatic access to the instance or class.
Detailed Answer
The three method types side by side
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
def add_topping(self, topping): # instance method: needs a specific pizza
self.toppings.append(topping)
@classmethod
def margherita(cls): # classmethod: alternative constructor
return cls(["mozzarella", "tomato"])
@staticmethod
def is_valid_topping(name): # staticmethod: no self/cls needed
return name.lower() in KNOWN_TOPPINGS
add_toppingneedsselfbecause it mutates a specific pizza's toppings — calling it makes no sense without an instance.margheritais a factory method:Pizza.margherita()builds a new instance without the caller needing to know the constructor's exact argument list.clsrefers to the actual class it's called on, so a subclass callingmargherita()correctly builds that subclass, not hard-coded toPizza.is_valid_toppingdoesn't touch instance or class state at all. It's grouped insidePizzapurely for namespacing/discoverability (Pizza.is_valid_topping("basil")), and could just as well be a module-level function.
Why classmethod respects subclassing and staticmethod doesn't apply
class StuffedCrustPizza(Pizza):
pass
StuffedCrustPizza.margherita() # returns a StuffedCrustPizza, not a Pizza!
Because margherita uses cls(...) rather than Pizza(...), calling it
on a subclass constructs the subclass. This is the main reason to prefer
@classmethod factories over hardcoding the class name.
When to choose which
| Need | Choice |
|---|---|
| Operates on instance data | instance method |
| Alternative constructor / needs the actual class | @classmethod |
| Utility function that's logically related but touches no instance/class state | @staticmethod (or just a module function) |
Instance methods operate on self.
Classmethods operate on cls and are the standard pattern for alternative
constructors that respect subclassing. Staticmethods are plain functions
namespaced under a class with no implicit self/cls access at all.