In: Computer Science
Python: Using Inheritance to Create a Derived Class in Python
In this lab, you create a derived class from a base class, and then use the derived class in a Python program. The program should create two Motorcycle objects, and then set the Motorcycle’s speed, accelerate the Motorcycle object, and check its sidecar status.
Instructions
motorcycle.py:
#Vehicle is a parent class
class Vehicle:
def accelarate(self,a):
print(a)
#Motorcycle is child class inherits vehicle class
class Motorcycle(Vehicle):
def __init__(self):
self.maxSpeed=0
self.currentSpeed=0
self.sidecar=True
#setMethod is used to set sidecar value
def setMethod(self,x):
self.sidecar=x
#getMethod is used to retrieve sidecar value
def getMethod(self):
return self.sidecar
#accelerate method is used to set accceleration
def accelerate(self,a):
if (self.currentSpeed + a ) > self.maxSpeed:
print("This motorcycle cannot go that fast")
else:
self.currentSpeed += a
#This is the get method to find the current speed
def findSpeed(self):
return self.currentSpeed
#This method is used to check sidecar status
def checkSideCar(self):
if self.sidecar:
print("This motorcycle has a sidecar")
else:
print("This motorcycle does not have a sidecar")
MyMotorcycleClassProgram.py:
#Motorcycle is imported from motorcycle.py
from motorcycle import Motorcycle
#motorcycle objects are created
motorcycleOne=Motorcycle()
motorcycleTwo=Motorcycle()
#to set the sidecar value
motorcycleOne.setMethod(True)
motorcycleTwo.setMethod(False)
#to set the maximum speed of motorcycle
motorcycleOne.maxSpeed=90
motorcycleTwo.maxSpeed=85
#to set the speed of motorcycle
motorcycleOne.currentSpeed=65
motorcycleTwo.currentSpeed=60
#to set the acceleration of motorcycle
motorcycleOne.accelerate(30)
motorcycleTwo.accelerate(20)
print("The speed of motorcycleOne :
",motorcycleOne.findSpeed())
print("The speed of motorcycleTwo :
",motorcycleTwo.findSpeed())
motorcycleOne.checkSideCar()
motorcycleTwo.checkSideCar()
Output:
This motorcycle cannot go that fast
The speed of motorcycleOne : 65
The speed of motorcycleTwo : 80
This motorcycle has a sidecar
This motorcycle does not have a sidecar