This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Inheritance - Another example

Here is another (more serious) example of inheritance. A square is a special type of rectangle.

class Rectangle:
    def __init__(self, width, height, center=(0, 0)):
        self.width = width
        self.height = height
        self.center = center

    def compute_area(self):
        return self.width * self.height


class Square(Rectangle):
    def __init__(self, side, center=(0, 0)):
         # equivalent to Rectangle.__init__(self, side, side, center)
        super().__init__(side, side, center)

In this example, Square hardly need to do anything except to call the constructor to the superclass Rectangle with the same width and height.

Multiple inheritance

Multiple inheritance occurs when a subclass can have more than one superclass.

class Parent1:
    pass

class Parent2:
    pass

class Subclass(Parent1, Parent2):
    pass

Inheriting from multiple classes can cause some problems. For example, if both Parent1 and Parent2 has a cook() method, then which version of cook() should Subclass inherit?

Python uses a method call Method Resolution Order (MRO) to determine the order in which an attribute is searched. The search is first done in the current class, and , if not found, continues into parent classes in depth-first, left-right order.

For more details, try this article