Full answer
python
from datetime import date
class Student:
def __init__(self, name, born):
self.name, self.born = name, born
@classmethod
def from_csv(cls, line):
name, year = line.split(",")
return cls(name.strip(), date(int(year), 1, 1))
@staticmethod
def is_valid_name(name):
return name.replace(" ", "").isalpha()
def __repr__(self):
return f"{type(self).__name__}({self.name!r}, {self.born.year})"
class Intern(Student):
pass
print(Student.from_csv("Asha Rao, 2004"), Intern.from_csv("Ben, 2006"))
print(Student.is_valid_name("Asha Rao"), Student.is_valid_name("R2D2"))Output:
text
Student('Asha Rao', 2004) Intern('Ben', 2006)
True FalseIntern.from_csv returns an Intern, because cls is whichever class the method was called on; a staticmethod that hard-coded Student(...) would lose that. is_valid_name needs no instance or class data, so it is a staticmethod; a module-level function would work equally well. Familiar library examples are dict.fromkeys and datetime.fromisoformat, both classmethods. Choose a regular method whenever the code needs instance data, a classmethod when it needs the class, and a staticmethod only for helpers that belong with the class conceptually.
python
from datetime import date
class Student:
def __init__(self, name, born):
self.name, self.born = name, born
@classmethod
def from_csv(cls, line):
name, year = line.split(",")
return cls(name.strip(), date(int(year), 1, 1))
@staticmethod
def is_valid_name(name):
return name.replace(" ", "").isalpha()
def __repr__(self):
return f"{type(self).__name__}({self.name!r}, {self.born.year})"
class Intern(Student):
pass
print(Student.from_csv("Asha Rao, 2004"), Intern.from_csv("Ben, 2006"))
print(Student.is_valid_name("Asha Rao"), Student.is_valid_name("R2D2"))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- classmethod receives cls
- Alternative constructors use classmethod
- Subclasses get the right type
- staticmethod is a namespaced function
- Module functions are often as good
Common mistakes
- Hard-coding the class name in factories
- Using staticmethod for code that needs class data
Follow-ups
- How would you register subclasses automatically?
- What does __init_subclass__ do?
Tips
- Show the subclass factory