Inheritance
You don’t always have to start from scratch when writing a class. If the class you’re writing is a specialized version of another class you wrote, you can use inheritance. When one class inherits from another, it automatically takes on all the attributes and methods of the first class. The original class is called the parent class, and the new class is the child class. The child class inherits every attribute and method from its parent class but is also free to define new attributes and methods of its own.
class Car():
"""A simple attempt to represent a car."""
def init(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class."""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name()) # 2016 Tesla Model S
When you create a child class, the parent class must be part of the current file and must appear before the child class in the file, as we define the child class, ElectricCar.
The name of the parent class must be included in parentheses in the definition of the child class. The init() method at w takes in the information required to make a Car instance.
The super() function at x is a special function that helps Python make connections between the parent and child class. This line tells Python to call the init() method from ElectricCar’s parent class, which gives an ElectricCar instance all the attributes of its parent class. The name super comes from a convention of calling the parent class a superclass and the child class a subclass.
We test whether inheritance is working properly by trying to create an electric car with the same kind of information we’d provide when making a regular car. At y we make an instance of the ElectricCar class, and store it in my_tesla. This line calls the init() method defined in ElectricCar, which in turn tells Python to call the init() method defined in the parent class Car. We provide the arguments ’tesla’, ‘model s’, and 2016.
Aside from init(), there are no attributes or methods yet that are particular to an electric car. At this point we’re just making sure the electric car has the appropriate Car behaviors:
Overriding Methods from the Parent Class
You can override any method from the parent class that doesn’t fit what you’re trying to model with the child class. To do this, you define a method in the child class with the same name as the method you want to override in the parent class. Python will disregard the parent class method and only pay attention to the method you define in the child class.
Say the class Car had a method called fill_gas_tank(). This method is meaningless for an all-electric vehicle, so you might want to override this method. Here’s one way to do that:
def ElectricCar(Car):
--snip--
def fill_gas_tank():
"""Electric cars don't have gas tanks."""
print("This car doesn't need a gas tank!")
Now if someone tries to call fill_gas_tank() with an electric car, Python will ignore the method fill_gas_tank() in Car and run this code instead. When you use inheritance, you can make your child classes retain what you need and override anything you don’t need from the parent class.
Reference
- Python Crash Course (2nd Edition) : A Hands-On, Project-Based Introduction to Programming
- Learning Python