What is the difference between @classmethod and @staticmethod?medium

Type
conceptual
Topic
classmethod-staticmethod
Frequency
common
Tags
classmethod, staticmethod, property, OOP, MRO
Answer

@classmethod receives the class (cls) as its first argument and is used for alternative constructors or factory methods. @staticmethod receives no implicit first argument and is just a utility function namespaced under the class.

Explanation

Instance methods get self (the instance), class methods get cls (the class itself), and static methods get neither. A common @classmethod pattern is a from_dict or from_json factory: Document.from_dict(data) creates an instance without manually calling the constructor. @property lets you expose computed attribute access so callers use obj.word_count instead of obj.word_count(), and a setter can add validation. __repr__ is for developers (unambiguous, used in the REPL); __str__ is for end users. Python uses MRO (Method Resolution Order) for multiple inheritance — inspect it with ClassName.__mro__.

Follow-upWhen would you use @classmethod over @staticmethod?
Follow-upWhat is @property and when would you use it?
Follow-upHow does MRO work in multiple inheritance?