A base class for aircraft

As usual, this will make much more sense with an example. We would like our aircraft classes AirbusA319 and Boeing777 to provide a way of returning the total number of seats. We’ll add a method called num_seats() to both classes to do this:

def num_seats(self):
rows, row_seats = self.seating_plan()
return len(rows) * len(row_seats)

The implementation can be identical in both classes, since it can be calculated from the seating plan.

Unfortunately, we now have duplicate code across two classes, and as we add more aircraft types the code duplication will worsen.

The solution is to extract the common elements of AirbusA319 and Boeing777 into a base class from which both aircraft types will derive. Let's recreate the class Aircraft, this time with the goal of using it as a base class:

class Aircraft:

def num_seats(self):
rows, row_seats = self.seating_plan()
return len(rows) * len(row_seats)

The Aircraft class contains just the method we want to inherit into the derived classes. This class isn't usable on its own because it depends on a method called seating_plan() which isn't available at this level. Any attempt to use it standalone will fail:

>>> from airtravel import *
>>> base = Aircraft()
>>> base.num_seats()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./airtravel.py", line 125, in num_seats
rows, row_seats = self.seating_plan()
AttributeError: 'Aircraft' object has no attribute 'seating_plan'

The class is abstract in so far as it is never useful to instantiate it alone.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset