Skip to content

Instantly share code, notes, and snippets.

@Ryanb58
Last active April 8, 2016 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ryanb58/3b4508fc0cebd78dd1397278e93a6e0f to your computer and use it in GitHub Desktop.
Save Ryanb58/3b4508fc0cebd78dd1397278e93a6e0f to your computer and use it in GitHub Desktop.
Starter example of polymorphism using python.
# Base Vehicle:
class Vehicle:
# Constructor
def __init__(self, owner):
self.owner = owner
def get_owner(self):
return self.owner
# Methods in which every subclass will be required to implement.
def top_speed(self):
raise NotImplementedError("Subclass is missing it's top speed method.")
# Vehicles:
class Truck(Vehicle):
def top_speed(self):
return "The truck has a top speed of 120mph."
class Sedan(Vehicle):
def top_speed(self):
return "The sedan has a top speed of 140mph."
class SportsCar(Vehicle):
def top_speed(self):
return "The sportscar has a top speed of 200mph."
vehicles = [
Truck("Chris"),
Sedan("Kyle"),
Sedan("Justin"),
SportsCar("John"),
]
for vehicle in vehicles:
print(vehicle.get_owner())
print(" * " + str(vehicle.top_speed()))
"""
Chris
* The truck has a top speed of 120mph.
Kyle
* The sedan has a top speed of 140mph.
Justin
* The sedan has a top speed of 140mph.
John
* The sportscar has a top speed of 200mph.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment