Lesson 48 of 60
โฎPrev Nextโฏ

PY-101 ยท Object-oriented Python

Inheritance

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

48of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    Inheritance lets a new class (the child) start from an existing class (the parent) and get all its attributes and methods, written class Child(Parent):. The child can add new methods or override existing ones, and call the parent's version with super(). It avoids copying code between similar classes.

    • Create a child class
    • Override a method
    • Call the parent with super()

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Inheritance, running
    1. class Employee:
    2. def __init__(self, name, salary):
    3. self.name = name
    4. self.salary = salary
    5. def describe(self):
    6. return f"{self.name} earns {self.salary}"
    7. class Manager(Employee):
    8. def __init__(self, name, salary, team):
    9. super().__init__(name, salary)
    10. self.team = team
    11. def describe(self):
    12. return super().describe() + f" and leads {len(self.team)} people"
    13. m = Manager("Asha", 90000, ["Ravi", "Li"])
    14. print(m.describe())
    15. print(isinstance(m, Employee))
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemA company has employees and managers. Managers are employees too, with one extra thing: a team. Copying the whole Employee class would mean fixing every bug twice.
    2. The Python ideaclass Child(Parent):Inheritance lets a new class (the child) start from an existing class (the parent) and get all its attributes and methods, written class Child(Parent):.
    3. In real lifeIn Django you write class Order(models.Model): and inherit saving, loading and querying without writing any of it.

    Start with a question

    A company has employees and managers. Managers are employees too, with one extra thing: a team. Copying the whole Employee class would mean fixing every bug twice.

    Frameworks are built on inheritance: you subclass their base classes to plug in your own behaviour.

    Explain it like I'm 10

    A child class is like a phone's new model: it keeps everything the old model did, adds a better camera, and maybe changes one or two things.

    The technical explanation

    class Manager(Employee): gives Manager everything Employee has.

    Defining a method with the same name overrides it. super().__init__(...) runs the parent's version first.

    isinstance(m, Employee) is True for a Manager, because a Manager is an Employee.

    Syntax

    class Child(Parent):
        def __init__(self, a, b):
            super().__init__(a)
            self.b = b

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    In Django you write class Order(models.Model): and inherit saving, loading and querying without writing any of it.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. How do you write a child class of Animal?
    2. 2. What does super() do?
    3. 3. A child defines a method with the parent's name. This is?
    4. 4. isinstance(Manager(...), Employee) when Manager inherits Employee?
    5. 5. Use inheritance for which relationship?

    Questions people ask

    Does Python support multiple inheritance?

    Yes: class C(A, B):. Python uses the method resolution order (C.__mro__) to decide which parent's method wins. Keep it simple and use it sparingly.

    What is composition vs inheritance?

    Inheritance: a class is a specialised version of another. Composition: a class holds other objects as attributes. Prefer composition when the relationship is "has a".

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner Does Python support multiple inheritance?

    Yes: class C(A, B):. Python uses the method resolution order (C.__mro__) to decide which parent's method wins. Keep it simple and use it sparingly.

    beginner What is composition vs inheritance?

    Inheritance: a class is a specialised version of another. Composition: a class holds other objects as attributes. Prefer composition when the relationship is "has a".

    intermediate How do you write a child class of Animal?

    class Dog(Animal):. Put the parent in brackets.

    intermediate What does super() do?

    Calls the parent class's version. It reaches the parent's methods.

    Quick revision

    Remember

    • Create a child class
    • Override a method
    • Call the parent with super()
    • Use inheritance for "is a" relationships (a Manager is an Employee). For "has a" (a Car has an Engine), store one object inside another instead.

    Syntax

    class Child(Parent):
        def __init__(self, a, b):
            super().__init__(a)
            self.b = b

    Official documentation