Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. What is polymorphism?

Python · Object-Oriented Python

What is polymorphism?

Mediumpython-23
polymorphismduck-typingoopprotocol

Question

What is polymorphism in Python?

Solution

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.
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."

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext