Question presented to candidate:
"Python has @classmethod and @staticmethod. What is the difference between them and a normal method, when would you reach for each, and what actually happens when you call one?"
What a strong answer should cover:
- A normal method receives the instance (
self), a class method receives the class (cls), a static method receives nothing extra β it is a plain function namespaced in the class. - Class methods are the tool for alternative constructors (
dict.fromkeys,datetime.fromtimestamp) becausecls(...)builds the subclass when called on a subclass; a static method has to hard-code the class. - Both can be called on the class or an instance; a class method called through an instance still gets the class.
- Mechanism: both are descriptors stored in the class
__dict__;classmethod.__get__returns a method bound to the class,staticmethod.__get__returns the underlying function unchanged. - Version facts: since Python 3.10 a
staticmethodobject is itself callable and both expose__wrapped__; chaining@classmethodover@propertywas deprecated in 3.11 and removed in 3.13. - Choosing: use a static method for a helper that needs neither the instance nor the class (or a module-level function), a class method when the class itself matters.
Code / implementation expected: Yes β a class with all three method kinds, an alternative constructor via @classmethod, and a subclass showing the difference.