Inheritance and Polymorphism
00:10 We’ve been able to define all of the attributes and methods that our objects are going to use and we’ve provided access to them. In these next few lessons, we’re going to take a look at how Python implements inheritance and polymorphism.
00:25 Remember, inheritance allows one class to derive all of the methods and attributes from a superclass. Typically, we have a general object description as our superclass, like a vehicle, and then our subclasses are more specific versions—a car or a boat.
00:56 And then we would put into those subclasses details specific to a car or a boat. Polymorphism allows you to use the same name for different subclass actions—attributes, methods—and the correct one will be used based on what type of object calls it.
And just to give us something different to compare to, we’ll say
.year is a feature we’re only interested in referring to cars. So we define the class
Vehicle and write the code necessary to handle
.model. And then to say class
Car inherits from
Vehicle, we put the superclass
Vehicle in parentheses, and that’s how we say that
Car inherits or extends
A more detailed version here. We can see that my initializer for
model to the appropriately newly-created attributes, and any methods that we have written to deal with color go in the
Vehicle class as well—the
.setColor(), the painting of the vehicle. In class
Car, we have said that it inherits from
The superclass one already does what we want it to do. We just have to provide functionality for those things that are new for cars. For example, the class variable for the number of wheels, the year of manufacturer, the number of cup holders, voltage—all of those things that we are putting specific to a car are defined in the
Car class. And any methods or actions—in this case, the property setter and getters for
._voltage—go in the
Car class, since that’s where that particular attribute is defined.
Just like in Java, you have to let the superclass deal with the parameters to the initializer that it’s responsible for. Instead of using the keyword
super, however, we specify the superclass, whose method we want to use.
The syntax in Python to use a superclass field method is to precede the method call with the class name, followed by the dot (
.) operator. Now to some other programmer using our
Car class, they aren’t going to see any difference functionally.
We can still perform the same actions that we did when it was just a single
Car class. So, we’re going to import
car and I can say
my_car = car.Car(), since it was still in the same file named
car. My silver
05:47 The fact that we use the superclass name specifically to call a superclass method—or, had we needed to, to access a superclass variable—allows us to do something in Python that we can’t do in Java, and that’s inheriting from more than one class.
Become a Member to join the conversation.