Skip to content

Instantly share code, notes, and snippets.

@davegotz
Created April 16, 2019 11:59
Show Gist options
  • Select an option

  • Save davegotz/16354122f8f7fe7a1d42ea2e976de16e to your computer and use it in GitHub Desktop.

Select an option

Save davegotz/16354122f8f7fe7a1d42ea2e976de16e to your computer and use it in GitHub Desktop.
Polymorphism Example
__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
# Move the vehicle
def move(self):
# All vehicles have a drive
print(self.driver + ":\t", end="")
# Each vehicle has its own sound!
self.make_sound()
# All vehicles have passengers
print(self.passengers)
# A default sound, for generic "Vehicles"
def make_sound(self):
for i in range(3):
print("Moving..", end="")
# 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)
# Override the make_sound method
def make_sound(self):
for i in range(3):
print("Vroom...", end="")
# 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)
# Override the make_sound method
# def make_sound(self):
# for i in range(3):
# print("Shhhh...", end="")
# 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")
airport_tram = Vehicle("Susan")
hawaii_taxi = GroundVehicle("Bob")
# Now let's put them into a list so we can treat them all as just "vehicles".
vacation_vehicles = [rdu_taxi, big_airplane, airport_tram, hawaii_taxi]
# Time for the trip. Let's go!
passengers = ["Anne", "David", "Sarah", "Issac", "Adina"]
for vehicle in vacation_vehicles:
vehicle.load(passengers)
vehicle.move()
passengers = vehicle.unload()
# Start the program.
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment