Using inheritance to simplify class definitions

We can use inheritance—reuse of code from a superclass in subclasses—which can simplify a subclass definition. In an earlier example, we created the MyAppError class as a subclass of Exception. This means that all of the features of Exception will be available to MyAppError. This works because of the three-step search for a name: if a method name is not found in an object's class, then the superclasses are all searched for the name.

Here's an example of a subclass which overrides just one method of the parent class:

class Manhattan_Point(Point):
    def dist(self, point):
        return abs(self.x-point.x)+abs(self.y-point.y)

We've defined a subclass of Point named Manhattan_Point. This class has all of the features ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.