Python Practice › OOP Programs › Program 6

Class method

EasyOOP Programs · 6 of 48

Write a Python class with a class method used as an alternative constructor.

Advertisement
Output
2 11 2026

Approach

  1. @classmethod receives the class as cls.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs