Content · Programming · Python

Python Polymorphism and Duck Typing Explained

Use polymorphism so different objects can implement the same operation.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Use polymorphism so different objects can implement the same operation.

How It Works


Duck typing emphasizes supported behavior rather than exact ancestry. If objects provide compatible methods, client code can call them without requiring every class to share the same parent.

Protocols and abstract base classes can make behavioral expectations explicit.

Step-by-Step Example


class CsvExporter:
    def export(self, records):
        return ",".join(records)

class TextExporter:
    def export(self, records):
        return " | ".join(records)

for exporter in [CsvExporter(), TextExporter()]:
    print(exporter.export(["alpha", "beta"]))

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The function definition gives the operation a reusable name and makes its inputs explicit.

A successful run of this example prints the following output:

alpha,beta
alpha | beta

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Build two formatter classes that both expose format(value).

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Assuming all polymorphic objects must inherit one specific base class.
  • Passing an object that lacks the expected method and not handling AttributeError.

Key Takeaways


  • Use polymorphism so different objects can implement the same operation.
  • Duck typing emphasizes supported behavior rather than exact ancestry.
  • Protocols and abstract base classes can make behavioral expectations explicit.
Share this resourceSend this page to someone who may find it useful.