00:00 Welcome to your next lesson in Object-Oriented programming in Python versus Java. In your last lesson, we looked at how Python implements inheritance. In this lesson, you’re going to see how multiple inheritance is implemented within Python. In Java, you can only inherit from one class and if you want to have multiple superclasses, all of the others have to be interfaces. Because when you’re within a subclass in Python to access the superclass you always have to specify the superclass name, we can allow subclasses to inherit directly from more than one superclass because each time we need a superclass item—attribute, method—we’ll be preceding it with its class name.
So, for example, if I define
Vehicle the way I had before, but now I define a class
Device—and we’ll see this class deals with the voltage, anything that can have voltage, say 12 volts, we’ll call it
Device—then we’ll want
Car to inherit from
The initializer for
Car is now going to have to call the
Vehicle initializer and the
Device initializer. But we can do that because we can specify which superclass’s
.__init__() method we’re going to call by preceding it with the class name.
So, we’ll send
Vehicle’s initializer by saying
Vehicle.__init__(). The voltage doesn’t need a parameter—that’s always set to
12—and so we don’t need any additional parameters except the calling object to send to the
Device’s initializer. And we’ll take a look at that code more closely now.
So here, all in the same file, we can define all of the classes that are related to each other in a single module, in a single Python file if we want. So here is my
Vehicle—again, dealing with color and model.
We let the
Vehicle initializer deal with color and model, and we let the
Device initializer deal with voltage. And then any references to those fields from the
Car class will also be passed along to the superclasses because the
Car inherits all of those properties. And again, I’ve not changed the functionality of the
Car class. I’ve improved its design to make use of inheritance. So again, if I create
Become a Member to join the conversation.