Python · Object-Oriented Python

What is polymorphism?

Mediumpolymorphismduck-typingoopprotocol

Interview question

What is polymorphism in Python?

How to answer

The short answer

Polymorphism means the same operation can work on different types. In Python that is mostly duck typing: if an object supports the needed methods/protocol, you can use it, regardless of its concrete class.

Forms you may mention:

  • Method overriding: subclasses provide different run() implementations.
  • Duck typing: len(), for x in obj, file-like objects.
  • Operator overloading: __add__, __iter__, etc.
Python
class CsvSource:
    def read(self):
        return ["a,1", "b,2"]

class ApiSource:
    def read(self):
        return ["c,3"]

def load_all(source):
    # polymorphic: only needs .read()
    return source.read()

print(load_all(CsvSource()))
print(load_all(ApiSource()))

# Built-in polymorphism
print(len("abc"), len([1, 2, 3]), len({"x": 1}))

Python also supports formal static polymorphism via typing.Protocol for structural typing with type checkers.

One-liner: "Call the same method name on different objects; each type does the right thing."

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill