Python 3D Academyবাংলা

Inheritance & Polymorphism in Python

Chapter 22: Inheritance & Polymorphism

6 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. Inheritance: building on a class

    class Child(Parent): makes a new class that inherits every attribute and method of the parent, and can add its own.

  2. Overriding methods and super()

    A child overrides a parent's method by writing one with the same name, and super().method() still lets it run the parent's version too.

  3. Polymorphism: one call, many shapes

    If different classes have a method with the same name, one line like shape.area() works on all of them, and each answers its own way.

  4. isinstance, and when to inherit

    isinstance(obj, Class) is True for objects of that class and of its children, and you should inherit only when "child is a parent" is true; otherwise keep one object inside another.

  5. Your own exceptions: a family of errors

    An exception is just a class, so you make a new kind of error by inheriting from Exception, and a whole family of them by inheriting from your own.

  6. Several parents: multiple inheritance and the MRO

    With several parents, Python still searches one fixed list of classes, the MRO (method resolution order), and you can see it with Duck.mro.