Tools
Log in
English

Learn to codePython

Python polymorphism

Based on Python 3.12

One save() call, three exporters: polymorphism and duck typing in Python.

In one line

One method name, different behavior for each object. Python checks whether an object has the method rather than which class it belongs to (duck typing), so you get this without inheritance too.

Why you need it

If every new export format (CSV, JSON, Excel) adds another if fmt == ... line, you must edit every function that has that chain. Miss one, and that format quietly breaks.

Give each format its own class with a method of the same name, and the calling code stays one line: t.save(row). A new format is one new class.

Everyday picture

Think of a wall socket. The wall does not know whether a fan or a phone charger is plugged in; if the plug fits, it supplies power, and each device does its own thing. The plug shape is the method name, the devices are the objects.

Example code

main.py · 39 lines
import json  class Exporter:    label = "base"     def export(self, row):        raise NotImplementedError     def save(self, row):        return f"[{self.label}] {self.export(row)}"  class CsvExporter(Exporter):    label = "csv"     def export(self, row):        return ",".join(str(v) for v in row.values())  class JsonExporter(Exporter):    label = "json"     def export(self, row):        return json.dumps(row)  class LineLogger:    label = "line"     def save(self, row):        return f"[{self.label}] " + " ".join(f"{k}={v}" for k, v in row.items())  row = {"name": "kim", "age": 31}targets = [CsvExporter(), JsonExporter(), LineLogger()]for t in targets:    print(t.save(row))print([isinstance(t, Exporter) for t in targets])

When to use it

  • There are several ways to do the same job (file formats, payment methods, notification channels)
  • The same if type(x) is ... check appears in several functions
  • Tests should pass in a fake object that has the same methods as the real one

Duck typing is convenient, but a missing method only shows up when the code runs. To demand certain methods up front, use an abstract base class (next topic) or typing.Protocol.

Common mistakes

Branching on the class with if chains

Every new format (Xml) means hunting down the if chain, and if you forget, you silently get None. Move the behavior into each class as a method, and adding a format means adding a class.

Wrong

class Csv:    pass  class Json:    pass  class Xml:    pass  def export(target):    if type(target) is Csv:        return "csv"    elif type(target) is Json:        return "json"  print(export(Xml()))

When you run itNone

Fixed

class Csv:    def export(self):        return "csv"  class Json:    def export(self):        return "json"  class Xml:    def export(self):        return "xml"  print(Xml().export())

When you run itxml

A typo in the method you meant to override

exprot is just a new method, so it never replaces export. The parent version runs and raises NotImplementedError. The names must match exactly.

Wrong

class Exporter:    def export(self, row):        raise NotImplementedError  class SemicolonExporter(Exporter):    def exprot(self, row):        return ";".join(row)  print(SemicolonExporter().export(["a", "b"]))

When you run itNotImplementedError

Fixed

class Exporter:    def export(self, row):        raise NotImplementedError  class SemicolonExporter(Exporter):    def export(self, row):        return ";".join(row)  print(SemicolonExporter().export(["a", "b"]))

When you run ita;b

Mixing in a value without the method

Duck typing checks nothing up front. The string "json" has no save, and the error only appears when the loop reaches it. Keep the list to objects with the same method.

Wrong

row = {"name": "kim", "age": 31}for t in [CsvExporter(), "json"]:    print(t.save(row))

When you run itAttributeError: 'str' object has no attribute 'save'

Fixed

row = {"name": "kim", "age": 31}for t in [CsvExporter(), JsonExporter()]:    print(t.save(row))

When you run it[csv] kim,31 [json] {"name": "kim", "age": 31}

Check yourself

Question 1

Robot does not inherit from Exporter. Can it join the same loop if it has save(row)?

class Robot:    label = "bot"     def save(self, row):        return f"[{self.label}] {len(row)} fields"  for t in [CsvExporter(), Robot()]:    print(t.save({"a": 1, "b": 2}))

Show the answer

Answer: 1. Yes, it has `save(row)` The loop only calls t.save(row). Any class with that method works. That is duck typing.

Question 2

What does JsonExporter().save({"x": 1}) return?

print(JsonExporter().save({"x": 1}))

Show the answer

Answer: 2. [json] {"x": 1} save comes from the parent, but self.label is looked up on the object's class first, so it is json.

Questions people ask

What is duck typing?

Ignoring an object's class and checking only that it has the method you need. Anything with save() can take the same place in the code.

Does polymorphism work without inheritance?

Yes. Python calls the method by name, so matching names are enough. Add inheritance when you also want to share code.

Is checking with isinstance wrong?

It works, but once you branch on classes with if, every new class means more edits. Keep the behavior in each class's own method.