Sub topic 6
Why cls matters: class methods and subclasses
This chapter assumes you can define classes, write instance methods that use self, and read the @name decorator syntax. It also assumes you know that a class attribute is shared by instances and an instance attribute belongs to one object. Earlier chapters introduced @classmethod and alternative constructors. This chapter covers what cls does when a subclass is involved.
cls is the class the call started from
A class method receives the class it was called on, not the class where it was written. When you call Square.create(), Python passes Square as cls, even though create is defined in Shape.
class Shape:
@classmethod
def create(cls):
return cls()
class Square(Shape):
pass
print(type(Shape.create()).__name__) # Shape
print(type(Square.create()).__name__) # SquareThe method body is identical in both calls. Only the value of cls changes. The diagram shows the path for the Square call.
The cost of hard-coding the class name
The most common mistake is to write the class name inside a class method instead of using cls. The code works for the base class and fails quietly for 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 Date(year, month, day) # hard-coded: ignores cls
class IsoDate(Date):
def __str__(self):
return f"{self.year}-{self.month:02d}-{self.day:02d}"
d = IsoDate.from_string("2026-11-26")
print(type(d).__name__) # Date, not IsoDate
print(hasattr(d, "__str__"), str(d) == "2026-11-26") # True FalseIsoDate.from_string returns a plain Date, so the custom __str__ is never used. No error is raised. The bug shows up later, wherever the code expects IsoDate behavior.
The fix is to build the instance through cls:
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 IsoDate(Date):
def __str__(self):
return f"{self.year}-{self.month:02d}-{self.day:02d}"
d = IsoDate.from_string("2026-11-26")
print(type(d).__name__) # IsoDate
print(d) # 2026-11-26Now the subclass inherits the alternative constructor and gets the right type without rewriting anything.
Subclasses with a different __init__
cls(...) calls the subclass's __init__, so the arguments you pass must match what that __init__ accepts. If a subclass changes the constructor signature, an inherited class method that calls cls(year, month, day) can fail.
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 Birthday(Date):
def __init__(self, year, month, day, name):
super().__init__(year, month, day)
self.name = name
try:
Birthday.from_string("2026-11-26")
except TypeError as error:
print(error) # Birthday.__init__() missing 1 required positional argument: 'name'You have two reasonable options. One is to override from_string in the subclass. The other is to keep the subclass signature compatible, for example by giving name a default value. Overriding is clearer when the extra data cannot be derived from the string.
class Birthday(Date):
def __init__(self, year, month, day, name="unknown"):
super().__init__(year, month, day)
self.name = name
b = Birthday.from_string("2026-11-26")
print(type(b).__name__, b.name) # Birthday unknownChanging class state through cls
Class methods can also read and write class attributes. The subtle point is that cls.attr = value assigns to the class held in cls. If the subclass has no such attribute yet, the assignment creates a new one on the subclass and leaves the parent's attribute alone.
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
class SubCounter(Counter):
pass
Counter.increment() # Counter.count becomes 1
SubCounter.increment() # reads 1 from Counter, writes 2 on SubCounter
print(Counter.count) # 1
print(SubCounter.count) # 2The expression cls.count += 1 first reads count through inheritance, then writes the result onto SubCounter. After that, the two classes track separate values. This is sometimes what you want, such as a separate registry per subclass. If you need one shared value, name the class explicitly, as in Counter.count += 1, or keep the state in a mutable object such as a list or dictionary that both classes reference.
| Goal | Write | Effect on a subclass call |
|---|---|---|
| Separate value per subclass | `cls.count += 1` | The subclass gets its own `count` after the first write |
| One value shared by all | `Counter.count += 1` | Parent and subclasses always see the same value |
| Shared mutable container | `cls.items.append(x)` | Mutates the one list that all classes reference |
Summary of the rule
- Use
cls(...)to create instances, so subclasses get their own type. - Keep subclass constructor signatures compatible with inherited class methods, or override those methods.
- Remember that assigning through
clswrites to the class the call started from.
Exercise
Given the code below, what does it print, and why? class Base: registry = [] @classmethod def register(cls, name): cls.registry = cls.registry + [name] class Child(Base): pass Base.register("a") Child.register("b") print(Base.registry, Child.registry)
Show answer
It prints ['a'] ['a', 'b']. Base.register("a") writes a new list onto Base. Child.register("b") reads ['a'] through inheritance, builds a new list ['a', 'b'], and assigns it to Child (assignment through cls creates Child.registry). Base.registry is unchanged. Using cls.registry.append(name) instead would mutate the single shared list, and both classes would print ['a', 'b'].
Exercise
A class method from_csv(cls, line) in Point ends with return Point(*values). Why is this a problem for a subclass Point3D, and what is the one-word change that fixes it?
Show answer
Point3D.from_csv(...) would return a plain Point, not a Point3D, because the class name is hard-coded and cls is ignored. Replace Point with cls: return cls(*values).