Intermediate LevelPython
What is the difference between @classmethod (receiving cls) and @staticmethod in Python classes?
❓ Interview Prompt: Compare `@classmethod` (receives class `cls` as first argument, factory constructors) vs `@staticmethod` (plain namespaced utility function).
1. '@classmethod' ('def foo(cls, ...)'):
•
Receives the class object 'cls' as its first argument.
•
Primary Use Case: Implementing alternative factory constructors (e.g. 'User.from_json(data)').
2. '@staticmethod' ('def foo(...)'):
•
Receives neither 'self' nor 'cls'.
•
Behaves like a plain function that is namespaced inside the class for logical organization.
Code Implementation Example
python
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod # Alternative Factory Constructor
def from_string(cls, date_str):
year, month, day = map(int, date_str.split('-'))
return cls(year, month, day)
@staticmethod # Utility helper
def is_valid_year(year):
return 1900 <= year <= 2100
d = Date.from_string('2026-07-28')💡Constructing objects via @classmethod factory constructor and @staticmethod helper.
🎯 Interview Key Takeaway
Use @classmethod for alternative factory constructors and @staticmethod for namespaced utility helpers.
#@classmethod#@staticmethod#OOP#Intermediate
Back to all Python Questions→