Created
April 16, 2019 11:59
-
-
Save davegotz/d4769c7bb748ef56f28ec45fd2471bd0 to your computer and use it in GitHub Desktop.
Inheritance Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| __author__ = 'David Gotz, gotz@unc.edu, Onyen = gotz' | |
| # Define the superclass Vehicle | |
| class Vehicle: | |
| # Define the initialization method | |
| def __init__(self, driver): | |
| self.driver = driver | |
| self.passengers = None | |
| # Load a list of passengers into the vehicle | |
| def load(self, passengers): | |
| self.passengers = passengers | |
| # Unload the list of passengers. Returns None if the vehicle is empty. | |
| def unload(self): | |
| passengers = self.passengers | |
| self.passengers = None | |
| return passengers | |
| # GroundVehicle: a subclass of Vehicle for ground transportation vehicles | |
| class GroundVehicle(Vehicle): | |
| # The initialization method | |
| def __init__(self, driver): | |
| # Call the superclass init | |
| Vehicle.__init__(self, driver) | |
| # Define a drive method | |
| def drive(self): | |
| print(self.driver + ": ", end="") | |
| for i in range(3): | |
| print("Vroom...", end="") | |
| print(self.passengers) | |
| # AirVehicle: a subclass of Vehicle for air transportation vehicles | |
| class AirVehicle(Vehicle): | |
| # The initialization method | |
| def __init__(self, driver): | |
| # Call the superclass init | |
| Vehicle.__init__(self, driver) | |
| # Define a fly method | |
| def fly(self): | |
| print(self.driver + ": ", end="") | |
| for i in range(3): | |
| print("Shhhh...", end="") | |
| print(self.passengers) | |
| # A main function to coordinate the program | |
| def main(): | |
| # Vacation time! We will need to drive to the airport, fly to our destination airport, then drive to the hotel. | |
| # That means two taxis and a plane | |
| rdu_taxi = GroundVehicle("Alice") | |
| big_airplane = AirVehicle("Jane") | |
| hawaii_taxi = GroundVehicle("Bob") | |
| # Now let's go! We will use: | |
| # 1. The same load method for all three vehicles | |
| # 2. Drive for cars. Fly for planes. These extend the base class Vehicle. | |
| passengers = ["Anne", "David", "Sarah", "Issac", "Adina"] | |
| rdu_taxi.load(passengers) | |
| rdu_taxi.drive() | |
| big_airplane.load(rdu_taxi.unload()) | |
| big_airplane.fly() | |
| hawaii_taxi.load(big_airplane.unload()) | |
| hawaii_taxi.drive() | |
| # Start the program. | |
| main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment