Sub topic 6
Why cls matters: class methods and subclasses
This chapter assumes you can write a class with instance methods and self. It also assumes you know the difference between class attributes and instance attributes, and you can read @name decorator syntax. The earlier chapters introduced @classmethod and alternative constructors. This one covers what happens when a class method runs on a subclass.
By the end you should be able to do four things:
- Predict which class a class method creates or modifies when it is called on a subclass.
- Write class methods that work for every subclass without edits.
- Override a class method and call the parent version with
super(). - Recognize the mistakes that make a class method behave wrongly in a subclass.
What cls actually is
When you call a class method, Python passes the class as the first argument. The key point is that it passes the class you called the method on. It does not pass the class where the method was written.
class Shape:
@classmethod
def create(cls):
return cls()
class Square(Shape):
pass
print(type(Shape.create()).__name__) # Shape
print(type(Square.create()).__name__) # Squarecreate is defined once, on Shape. Square inherits it. When you write Square.create(), Python looks up create, finds it on Shape through the inheritance chain, and binds cls to Square. The lookup location and the value of cls are separate things.
If the method had hard-coded return Shape(), both calls would give a Shape. Subclasses would silently lose their own type.
| How you call it | Value of `cls` |
|---|---|
| `Shape.create()` | `Shape` |
| `Square.create()` | `Square` |
| `Square().create()` | `Square` (the type of the instance) |
| `super().create()` inside a `Square` class method | The same `cls` that the calling method received |
The third row is worth remembering. Calling a class method through an instance does not pass the instance. Python takes type(instance) and passes that.
class Shape:
@classmethod
def create(cls):
return cls()
class Square(Shape):
pass
s = Square()
other = s.create()
print(type(other).__name__) # Square
print(other is s) # FalseThe method receives the class Square, builds a new object, and returns it. The original instance plays no part except for supplying its type.
Alternative constructors and subclasses
The most common use of this behavior is an alternative constructor. Here is a Date class with two parsers. One uses cls. The other hard-codes the class name.
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)
@classmethod
def from_string_hardcoded(cls, text):
year, month, day = map(int, text.split("-"))
return Date(year, month, day)
class PrettyDate(Date):
def __str__(self):
return f"{self.day:02d}/{self.month:02d}/{self.year}"
good = PrettyDate.from_string("2026-11-26")
bad = PrettyDate.from_string_hardcoded("2026-11-26")
print(type(good).__name__) # PrettyDate
print(type(bad).__name__) # Date
print(good) # 26/11/2026
print(bad) # <__main__.Date object at 0x...>Both methods are class methods and both ran on PrettyDate. The second one ignores cls and builds a Date, so the subclass's __str__ never applies. The bug does not raise an error. It produces an object of the wrong type, and you find it later when a method is missing or a display looks wrong.
The rule: inside a class method, build instances with cls(...), not with the class's own name.
When the subclass changes `__init__`
cls(...) assumes the subclass accepts the same constructor arguments as the parent. If a subclass changes the signature, inherited alternative constructors can break.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def origin(cls):
return cls(0, 0)
class Point3D(Point):
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
print(Point.origin().x) # 0
try:
Point3D.origin()
except TypeError:
print("TypeError: Point3D needs a z value")Point3D.origin() calls Point3D(0, 0), which lacks z. You have three reasonable fixes:
- Give the new parameter a default, as in
def __init__(self, x, y, z=0). - Override
originin the subclass. - Keep subclass constructors compatible with the parent's, so inherited class methods keep working.
Option 2 looks like this:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def origin(cls):
return cls(0, 0)
class Point3D(Point):
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
@classmethod
def origin(cls):
return cls(0, 0, 0)
p = Point3D.origin()
print(p.x, p.y, p.z) # 0 0 0Which option you choose depends on whether Point3D should be usable anywhere a Point is. If yes, prefer option 1 or 3. If the subclass is a deliberately different shape of object, option 2 is honest about that.
Reading class attributes through cls
A class method can read class attributes through cls, and each subclass can supply its own value. This gives you a simple customization hook.
class Polygon:
sides = 0
@classmethod
def describe(cls):
return f"{cls.__name__} has {cls.sides} sides"
class Triangle(Polygon):
sides = 3
class Hexagon(Polygon):
sides = 6
print(Polygon.describe()) # Polygon has 0 sides
print(Triangle.describe()) # Triangle has 3 sides
print(Hexagon.describe()) # Hexagon has 6 sidesdescribe is written once. cls.sides is resolved at call time against the class you started from, so each subclass's own value wins. cls.__name__ is the class's name as a string. Writing Polygon.sides inside the method would always give 0, for the same reason hard-coding the class in a constructor always gives the parent type.
Attribute lookup on a class follows the method resolution order (MRO). That is the list of classes Python searches, starting from the class itself and moving to its parents. A subclass that does not define sides gets the nearest parent's value.
Writing to class attributes through cls
Reading through cls is straightforward. Writing is trickier, because assignment does not follow inheritance the way lookup does.
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
class SubCounter(Counter):
pass
Counter.increment()
SubCounter.increment()
SubCounter.increment()
print(Counter.count) # 1
print(SubCounter.count) # 3
print("count" in SubCounter.__dict__) # TrueFollow what happens. The line cls.count += 1 is shorthand for cls.count = cls.count + 1. The right side reads count, which finds the inherited value. The left side writes count onto cls itself.
- The first call runs with
cls = Counter. It reads 0 and writesCounter.count = 1. - The second call runs with
cls = SubCounter. It reads the inherited 1 and writes a new attributeSubCounter.count = 2. From now onSubCounterhas its owncountand no longer sees the parent's. - The third call reads
SubCounter.count(2) and writes 3.
So the two classes end up with separate counters, and the second one started from the parent's value. This is rarely what people intend. You have to decide which behavior you want and write the code to match.
If you want one counter shared by every subclass, name the owning class explicitly:
class Counter:
count = 0
@classmethod
def increment(cls):
Counter.count += 1
class SubCounter(Counter):
pass
Counter.increment()
SubCounter.increment()
SubCounter.increment()
print(Counter.count) # 3
print(SubCounter.count) # 3Here hard-coding the class name is the right choice, because the data is shared on purpose. If you want a separate counter per class from the start, give each class its own value, either in the class body or in __init_subclass__:
class Counter:
count = 0
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.count = 0
@classmethod
def increment(cls):
cls.count += 1
class SubCounter(Counter):
pass
Counter.increment()
SubCounter.increment()
SubCounter.increment()
print(Counter.count) # 1
print(SubCounter.count) # 2__init_subclass__ is a special hook that Python calls on the parent whenever a subclass is created. It is an implicit class method, so its first argument is the new subclass. Setting cls.count = 0 there gives every subclass a clean starting value.
A mutable class attribute, such as a list or dict, behaves differently. Mutating it does not assign to cls, so the object stays shared:
class Plugin:
registry = []
@classmethod
def register(cls):
cls.registry.append(cls.__name__)
class CsvPlugin(Plugin):
pass
class JsonPlugin(Plugin):
pass
CsvPlugin.register()
JsonPlugin.register()
print(Plugin.registry) # ['CsvPlugin', 'JsonPlugin']
print(CsvPlugin.registry) # ['CsvPlugin', 'JsonPlugin']
print(CsvPlugin.registry is Plugin.registry) # Truecls.registry.append(...) reads registry through cls, finds the one list on Plugin, and mutates it. No assignment to cls happens, so no new attribute appears. This is a useful way to build a registry of subclasses. It is also a surprise if you expected each subclass to get its own list.
| Statement inside a class method | What it does |
|---|---|
| `cls.attr` (read) | Looks up `attr` along the MRO of `cls` |
| `cls.attr = value` | Creates or replaces `attr` on `cls` only |
| `cls.attr += 1` | Reads along the MRO, then assigns on `cls` only |
| `cls.items.append(x)` | Mutates whichever object lookup finds, shared by all classes that inherit it |
Overriding class methods and calling super()
A subclass can override a class method as it would any other method. To extend the parent's version instead of replacing it, use super().
class Animal:
def __init__(self, name):
self.name = name
@classmethod
def from_string(cls, text):
return cls(text.strip().title())
class Dog(Animal):
@classmethod
def from_string(cls, text):
dog = super().from_string(text)
dog.name = dog.name + " the dog"
return dog
rex = Dog.from_string(" rex ")
print(type(rex).__name__) # Dog
print(rex.name) # Rex the dog
generic = Animal.from_string(" tom ")
print(type(generic).__name__) # Animal
print(generic.name) # TomInside Dog.from_string, super().from_string(text) finds the parent's class method and binds it to the current cls. Here that is Dog, so the parent's cls(...) call builds a Dog. If super() passed Animal, the result would be an Animal and the Dog override would be pointless. The parent code does the shared work and the child adds its own step.
This is the main reason to use cls over the class name. A subclass can extend the parent's constructor logic without copying it.
Class methods are not overridden by instance state
One more detail concerns name lookup. An instance attribute can shadow a class method with the same name. This is rare, but it shows that cls binding only happens when the lookup reaches the class.
class Config:
@classmethod
def load(cls):
return f"loaded by {cls.__name__}"
c = Config()
print(c.load()) # loaded by Config
c.load = lambda: "instance override"
print(c.load()) # instance override
print(Config.load()) # loaded by ConfigAssigning c.load puts a plain function in the instance's __dict__. Instance attributes take priority over non-data descriptors, so the lambda wins for that one object. The class method on the class is unchanged. You will seldom do this on purpose, but it explains confusing results if an attribute is assigned accidentally.
A worked design: a base class with several loaders
Here is a small example that uses everything above. A Record base class has two alternative constructors. Subclasses supply their own field list through a class attribute.
class Record:
fields = ()
def __init__(self, **values):
for name in self.fields:
setattr(self, name, values[name])
@classmethod
def from_csv_line(cls, line):
parts = [p.strip() for p in line.split(",")]
return cls(**dict(zip(cls.fields, parts)))
@classmethod
def from_dict(cls, data):
return cls(**{name: data[name] for name in cls.fields})
def __repr__(self):
pairs = ", ".join(f"{n}={getattr(self, n)!r}" for n in self.fields)
return f"{type(self).__name__}({pairs})"
class User(Record):
fields = ("name", "email")
class Product(Record):
fields = ("sku", "price")
print(User.from_csv_line("Ada, [email protected]"))
# User(name='Ada', email='[email protected]')
print(Product.from_dict({"sku": "A1", "price": "9.99", "extra": "ignored"}))
# Product(sku='A1', price='9.99')Neither from_csv_line nor from_dict mentions User or Product. Each reads cls.fields and builds cls(...), so one implementation serves every subclass. Adding a new record type means writing a class with a fields tuple and nothing else.
Pitfalls specific to subclasses
- Hard-coding the class name. Writing
return Date(...)in a class method returns the parent type for every subclass. Usecls(...). - Assuming
cls.x += 1updates a shared value. It creates a per-subclass attribute the first time a subclass runs it. Name the owning class if you want sharing. - Forgetting that subclasses can change
__init__. Inherited constructors that callcls(...)fail withTypeErrorif the signature differs. - Expecting the instance to be passed.
instance.class_method()passestype(instance). If you need instance data, you want an instance method. - Calling
super()with the wrong form. Inside a class method, zero-argumentsuper()works and keepsclsbound correctly. WritingParent.method(text)directly bypasses the binding and can pass the wrong class.
Summary
cls is the class the call started from. Inheritance decides where Python finds the method, and the call decides what cls is. Building instances with cls(...) and reading settings through cls.attribute lets one method serve every subclass. Writing through cls creates attributes on the subclass, which is a common source of surprise. Mutating a shared object through cls leaves it shared.
Exercise
What does this program print, and why? class Base: total = 10 @classmethod def bump(cls): cls.total += 5 class Child(Base): pass Child.bump() print(Base.total, Child.total)
Show answer
It prints 10 15. Child.bump() runs with cls = Child. The statement cls.total += 5 reads the inherited value 10 from Base, then assigns 15 as a new attribute on Child. Base.total is never changed. To update the shared value, write Base.total += 5 instead.
Exercise
The class below has a bug that only shows up with subclasses. Find it and fix it. What does type(Admin.from_name("ann")).__name__ return before and after the fix?
class User:
def _init(self, name):
self.name = name
@classmethod
def fromname(cls, name):
return User(name.title())
class Admin(User):
pass
Show answer
The class method builds User(...) using the hard-coded name, so it ignores cls. Before the fix, type(Admin.from_name("ann")).__name__ returns 'User'. Change the body to return cls(name.title()). After the fix it returns 'Admin'.
Exercise
A Plugin base class keeps registry = [] and each subclass calls cls.registry.append(cls.__name__) in a class method. Does each subclass get its own list? What small change gives each subclass a separate list?
Show answer
No. cls.registry.append(...) only mutates the list found by lookup, which is the single list on Plugin, so every subclass shares it. To give each subclass its own list, define __init_subclass__(cls, **kwargs) on Plugin, call super().__init_subclass__(**kwargs), and set cls.registry = [] there. Each new subclass then gets its own list when the class is created.