Sub topic 5
Alternative constructors with @classmethod
Prerequisites
This chapter assumes you can define a Python class with __init__ and instance methods, and that you know what self refers to. It also assumes you have read the previous chapter on @classmethod and cls. A decorator is the @name line above a function. You do not need to know how decorators work internally.
The problem: one `__init__`, many sources of data
Python allows only one __init__ per class. Suppose a Date class takes year, month and day. Callers will also want to build a date from a string like "2026-11-26", from a timestamp, or from today's date.
You could cram all of this into __init__ with type checks and optional arguments. That makes the signature hard to read and the body full of branches. A cleaner approach is to keep __init__ simple and add named alternative constructors. An alternative constructor is a class method that builds and returns a new instance from some other kind of input.
A first alternative constructor
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, text):
year, month, day = map(int, text.split("-"))
return cls(year, month, day)
d = Date.from_string("2026-11-26")
print(d.year, d.month, d.day) # 2026 11 26Here is what happens when you call Date.from_string("2026-11-26"):
- Python passes the class
Dateascls, and the string astext. - The method splits the text on
-and converts each piece to anint. cls(year, month, day)calls the class, which runs__init__and returns a newDate.- The method returns that instance.
The key line is return cls(year, month, day). The method never creates an object by hand. It delegates to the normal constructor, so any validation or setup in __init__ still runs.
Naming conventions
Python's own library follows a pattern you can copy. Names usually start with from_ and describe the source of the data:
datetime.date.fromisoformat("2026-11-26")dict.fromkeys(["a", "b"])int.from_bytes(b"\x01\x00", "big")
Names such as from_string, from_dict or from_file tell the reader what input to pass. A name like today or empty suits constructors that take no data. Avoid vague names like create2 or make.
A second example: converting units
The Temperature class uses the same pattern with a calculation instead of parsing.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def to_fahrenheit(self):
return self.celsius * 9 / 5 + 32
@classmethod
def from_fahrenheit(cls, fahrenheit):
return cls((fahrenheit - 32) * 5 / 9)
t = Temperature.from_fahrenheit(212)
print(t.celsius) # 100.0
print(t.to_fahrenheit()) # 212.0__init__ stores Celsius, which is the class's internal representation. from_fahrenheit converts the input to that representation and then calls the regular constructor. Callers get a convenient entry point and the class keeps a single canonical form.
Why `cls(...)` and not `Date(...)`
You could write return Date(year, month, day) inside from_string, and it would work for Date itself. The problem appears with subclasses.
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, text):
year, month, day = map(int, text.split("-"))
return cls(year, month, day)
class LoggedDate(Date):
pass
d = LoggedDate.from_string("2026-11-26")
print(type(d).__name__) # LoggedDateWhen you call LoggedDate.from_string(...), cls is LoggedDate, so the result is a LoggedDate. If the method hard-coded Date, the subclass would silently get back a plain Date. It would lose any methods or attributes the subclass adds. The next chapter covers inheritance in more detail. For constructors, the rule is simple: always build the instance with cls.
Keeping `__init__` as the single point of truth
An alternative constructor should prepare the arguments and hand them to cls(...). It should not set attributes on a bare object itself. The following version works, but it duplicates the attribute logic:
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, text):
obj = cls.__new__(cls)
obj.year, obj.month, obj.day = map(int, text.split("-"))
return objThis skips __init__, so if you later add validation such as checking that month is between 1 and 12, from_string bypasses it. Calling cls(...) avoids that problem.
Adding validation in one place
Because every constructor path ends in __init__, a check placed there covers all of them.
class Date:
def __init__(self, year, month, day):
if not 1 <= month <= 12:
raise ValueError(f"month out of range: {month}")
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, text):
year, month, day = map(int, text.split("-"))
return cls(year, month, day)
try:
Date.from_string("2026-13-01")
except ValueError as error:
print(error) # month out of range: 13The string "2026-13-01" parses without trouble. The error comes from __init__, which from_string reached through cls(...).
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `@classmethod` | `TypeError` about a missing argument, because `Date.from_string("...")` passes the string as `cls` | Add the decorator above `def` |
| Writing `Date(...)` instead of `cls(...)` | Subclasses get back the base class | Use `cls(...)` |
| Bypassing `__init__` with `__new__` | Validation and defaults are skipped | Call `cls(...)` |
| Returning nothing | The caller receives `None` | End with `return cls(...)` |
Exercise
Add a from_timestamp alternative constructor to this class. It should take a Unix-style count of seconds and return a Clock with hours and minutes fields, where the seconds are counted from midnight. For example, Clock.from_seconds(3660) should give hours == 1 and minutes == 1. Use cls, not Clock.
class Clock:
def _init_(self, hours, minutes):
self.hours = hours
self.minutes = minutes
Show answer
Add a class method that divides the seconds and passes the result to cls:
@classmethod
def from_seconds(cls, seconds):
hours, remainder = divmod(seconds, 3600)
minutes = remainder // 60
return cls(hours, minutes)
For 3660 seconds, divmod(3660, 3600) gives (1, 60), and 60 // 60 is 1, so the result is Clock(1, 1). Because the method uses cls, calling it on a subclass of Clock returns that subclass.
Exercise
A teammate writes @classmethod def from_dict(cls, data): return Point(data["x"], data["y"]) inside Point. Later a Point3D(Point) subclass is added. What does Point3D.from_dict({"x": 1, "y": 2}) return, and how do you fix it?
Show answer
It returns a plain Point, not a Point3D, because the class name is hard-coded. Replace Point(...) with cls(...). Note that Point3D would also need a compatible __init__, or its own override of from_dict, if it takes extra arguments such as z.