Where a regular instance method's first parameter is self, a specific object, a classmethod's first parameter is cls, the class itself, and it can be called either on the class directly or on an instance — either way, cls always refers to the class. The most common use is an alternative constructor: a classmethod that builds and returns a new instance from a different kind of input than __init__ accepts, like parsing a string or a dictionary into an object.
1Understanding Class Methods (@classmethod)
Where a regular instance method's first parameter is self, a specific object, a classmethod's first parameter is cls, the class itself, and it can be called either on the class directly or on an instance — either way, cls always refers to the class. The most common use is an alternative constructor: a classmethod that builds and returns a new instance from a different kind of input than __init__ accepts, like parsing a string or a dictionary into an object.
Alternative constructors are the killer use case for @classmethod — instead of overloading __init__ with lots of optional parameters and flags for different construction styles, define separate, clearly-named classmethods for each one.
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@classmethod
def margherita(cls):
return cls(["tomato", "mozzarella", "basil"])
p = Pizza.margherita()
print(p.toppings)2Practical Example
Here is a real-world application of Class Methods (@classmethod) showing how it is used in production Python code.
class Date:
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_string(cls, date_string):
year, month, day = map(int, date_string.split("-"))
return cls(year, month, day)
d = Date.from_string("2026-07-23")
print(d.year, d.month, d.day)3Best Practices
Follow these guidelines when working with Class Methods (@classmethod):
1. Use @classmethod for alternative constructors instead of cramming multiple construction styles into one complicated __init__
2. Use cls(...) inside a classmethod rather than hardcoding the class name, so subclasses inherit the classmethod correctly and construct the right subclass
3. Reach for @staticmethod instead if the method doesn't actually need access to the class or any instance
Tip: Alternative constructors are the killer use case for @classmethod — instead of overloading __init__ with lots of optional parameters and flags for different construction styles, define separate, clearly-named classmethods for each one.
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@classmethod
def margherita(cls):
return cls(["tomato", "mozzarella", "basil"])
p = Pizza.margherita()
print(p.toppings)