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 of a Point
. It makes a single change to the parent class. It provides a definition for the dist()
method that will override the definition in the Point
superclass.
Here's an example that shows how...