← Python lessons

Python Dataclass Inheritance and Polymorphism

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Python dataclass inheritance gives a subclass its parent's fields and generated constructor. Polymorphism lets one method call run each object's own version.

Read Python Dataclass Methods first. The examples also use f-strings and the string methods upper() and lower(). This lesson makes a subclass of a dataclass, overrides one of its methods and calls that method on a list of mixed objects. Python Inheritance shows subclasses of ordinary classes.

Inherit a generated constructor

Put the parent class in brackets after the subclass name. A subclass that adds no fields needs no @dataclass of its own.

from dataclasses import dataclass@dataclassclass Message:    sender: str    text: strclass Shout(Message):    def loud(self):        return self.text.upper()shout = Shout("Ada", "lunch is ready")print(shout)print(shout.sender)print(shout.loud())

This prints Shout(sender='Ada', text='lunch is ready'), then Ada and LUNCH IS READY. Shout uses the fields, __init__() and __repr__() that @dataclass made for Message. The printed form still says Shout, because the generated __repr__() uses the object's own class name. Only loud() is new.

Leave @dataclass off a subclass that only adds or changes methods. It has nothing new to generate. A subclass that adds a field does need its own @dataclass. That makes a new __init__() taking the parent's fields first, then the new one.

Override one method

A subclass overrides a method by defining one with the same name. Its objects then use the new version, while parent objects keep the old one. The name decides what happens: a new name, like loud() above, adds a method, while a name the parent has, like show(), replaces the parent's version.

from dataclasses import dataclass@dataclassclass Message:    sender: str    text: str    def show(self):        return f"{self.sender}: {self.text}"class Shout(Message):    def show(self):        return f"{self.sender}: {self.text.upper()}!"print(Message("Ada", "lunch is ready").show())print(Shout("Ada", "lunch is ready").show())

This prints Ada: lunch is ready, then Ada: LUNCH IS READY!. Python looks for show() in the object's own class first. So a Shout never reaches Message.show(). Keep the parent's parameters (here just self), so every call to show() works on both.

One call, different implementations

Put objects of both classes in one list. The loop calls show() without asking which kind each object is.

from dataclasses import dataclass@dataclassclass Message:    sender: str    text: str    def show(self):        return f"{self.sender}: {self.text}"class Shout(Message):    def show(self):        return f"{self.sender}: {self.text.upper()}!"for message in [Message("Ada", "hi"), Shout("Sam", "goal"), Message("Lee", "bye")]:    print(message.show())

This prints Ada: hi, Sam: GOAL! and Lee: bye. Each object brings its own show(). That is polymorphism: the same call does what each object's class says.

Use it when objects share their fields but one rule differs. Without subclasses, show() would need an if for every kind of message. With them, each kind keeps its rule in its own class, and the loop stays the same when you add another kind.

Inheritance and composition are easy to mix up. Make a subclass when the new class is a kind of the parent: a shout is a message. When an object only has another object, store it in a field instead, as in Python OOP Composition with Dataclasses.

A misspelt override changes nothing

An override must use exactly the parent's method name. Any other name only adds a new method, so the parent's version still runs.

from dataclasses import dataclass@dataclassclass Message:    sender: str    text: str    def show(self):        return f"{self.sender}: {self.text}"class Shout(Message):    def shows(self):  # a different name, so not an override        return f"{self.sender}: {self.text.upper()}!"print(Shout("Sam", "goal").show())

This prints Sam: goal, with no error. Shout has no show(), so Python uses Message.show(). When a subclass seems to ignore your method, compare the two names first.

Note: The generated __eq__() checks that both objects have the same class before it compares fields. So Message("Ada", "hi") == Shout("Ada", "hi") is False. The overrides here replace the parent's method completely. Method overriding and super() shows how to build on its result instead.

See also: Python Inheritance, Python Frozen Dataclasses and replace.

Your turn

Add a Whisper subclass of Message. Its show() returns the sender, a colon, a space, then the text in lower case followed by ....

🎯 Goal — make it print exactly:
Ada: Hi
Lee: quiet please...
from dataclasses import dataclass@dataclassclass Message:    sender: str    text: str    def show(self):        return f"{self.sender}: {self.text}"# add a Whisper subclass of Message that overrides show()for message in [Message("Ada", "Hi"), Whisper("Lee", "Quiet Please")]:    print(message.show())