Preserve Subclass Results with Self
Core idea
Self (Python 3.11+) describes the concrete receiver type for methods returning that kind of instance. A classmethod factory can return Self when it constructs cls rather than a fixed base class. The annotation does not itself construct or validate the result.
from typing import Selfclass Meter: def reset(self)->Self: self.value=0 return selfclass Digital(Meter): passm=Digital()print(m.reset() is m, type(m).__name__)Returning self preserves the subclass object and enables chaining.
Construct through cls
from typing import Selfclass Tag: def __init__(self,name:str): self.name=name @classmethod def parse(cls,text:str)->Self: return cls(text.strip())class ShippingTag(Tag): passitem=ShippingTag.parse(' A ')print(type(item).__name__, item.name)The inherited factory calls the actual subclass; its constructor must accept the argument.
Common mistake
Do not annotate a method that always returns Base() with Self: subclass callers would receive an incorrect promise.
Practice
Create a subclass with a compatible constructor and a subclass-specific method; test chaining after the factory in a checker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Self and class methods
Check your understanding of self and class methods.
What is printed?
class A: @classmethod def make(cls): return cls()class B(A): passprint(type(B.make()).__name__)What is printed?
class A: def same(self): return selfa=A()print(a.same() is a)When is Self appropriate for a factory?
Does Self create an instance automatically?