Class Method
In one line
@classmethod receives cls (the class) instead of self — ideal for alternative constructors and factory methods.
In simple words
A @classmethod receives the class itself (cls) as its first argument instead of an instance (self). This lets it:
- Create alternative constructors — the most common use case (factory methods)
- Access/modify class-level state — class variables shared across instances
- Work with inheritance —
clsis the actual subclass, so class methods are inherited correctly
The classic pattern is from_string(), from_dict(), etc. — alternative ways to construct instances. When called on a subclass, cls is the subclass, enabling polymorphic construction.
Example
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_str):
# Alternative constructor: "2024-01-15"
year, month, day = map(int, date_str.split("-"))
return cls(year, month, day)
@classmethod
def today(cls):
import datetime
t = datetime.date.today()
return cls(t.year, t.month, t.day)
d = Date.from_string("2024-01-15")
print(d.year, d.month, d.day) # 2024 1 15
t = Date.today()
print(t.year)@classmethod receives cls (the class), enabling alternative constructors (factory methods). cls() creates instances polymorphically.
Common confusions
Confused with: static method
The difference: @classmethod receives cls (the class) as first arg — it can create instances and access class state. @staticmethod receives no implicit argument — it's a plain function that can't access class or instance state. Use classmethod for constructors, staticmethod for utilities.
Related terms
Related Resources
Related Lessons
- Python OOP
Class methods.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.