Fri Aug 06 2021
Polymorphism
Python Programming3667 views
File Name: polymorphism.py
#!/usr/bin/evn python
# Define a class as 'car'
class car:
# Constructor of the class
def __init__(self, name, spd):
self.name = name
self.speed = spd
# Abstract method, defined by convention only
def spdLtm(self):
raise NotImplementedError("Subclass must implement abstract method")
# Define a class as 'suv' and inherit 'car'
class suv(car):
# Redefine method with same name as super class
def spdLtm(self):
return 'SUV', self.speed
# Define a class as 'roadster' and inherit 'car'
class roadster(car):
# Redefine method with same name as super class
def spdLtm(self):
return 'Roadster', self.speed
# Array of objects
cars = [suv('Toyota Fortuner', '250km/h'),
roadster('Audi R8 Spyder', '314km/h'),
suv('Nissan V8', '280km/h')]
for car in cars:
print ('Car name', car.name, 'Top Speed of your', car.spdLtm())
#***** Output *****
# Car name Toyota Fortuner Top Speed of your ('SUV', '250km/h')
# Car name Audi R8 Spyder Top Speed of your ('Roadster', '314km/h')
# Car name Nissan V8 Top Speed of your ('SUV', '280km/h')
Reference:
Author:Geekboots