Python · Object-Oriented Python

What is inheritance?

Mediuminheritancesupermrooop

Interview question

What is inheritance in Python?

How to answer

The short answer

Inheritance lets a class (child/subclass) reuse and extend another class (parent/superclass). The child gets parent attributes/methods and can override or add behavior.

Python supports single and multiple inheritance. Method Resolution Order (MRO, C3) decides which parent method wins.

Python
class Job:
    def __init__(self, name):
        self.name = name

    def run(self):
        return f"running {self.name}"

class BatchJob(Job):
    def run(self):
        base = super().run()
        return base + " in batch mode"

class ScheduledMixin:
    def schedule(self, cron):
        self.cron = cron

class NightlyETL(ScheduledMixin, BatchJob):
    pass

job = NightlyETL("sales")
print(job.run())          # running sales in batch mode
job.schedule("0 2 * * *")
print(NightlyETL.mro())

Prefer composition when you only need to "have a" collaborator. Use inheritance for true "is a" relationships and shared polymorphic interfaces.

Interview tip: Mention super() and MRO when discussing multiple inheritance.

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