Python Practice › OOP Programs › Program 6
Class method
Write a Python class with a class method used as an alternative constructor.
Output
2 11 2026
Approach
@classmethodreceives the class ascls.
Solution
class Date: def __init__(self, day, month, year): self.day, self.month, self.year = day, month, year @classmethod def from_string(cls, text): day, month, year = map(int, text.split("-")) return cls(day, month, year) d = Date.from_string("02-11-2026")print(d.day, d.month, d.year)Output
2 11 2026
Line by line
Lines 5-8
from_string parses text and calls cls(...), so subclasses get objects of their own type.
Learn the concept
New to this topic? Read the lesson, then come back.