You are on page 1of 11

Section 7

polymorphism
Programming 2
Create class called Ferrari :
• Create two methods fuel_type and max_speed.
Example 1: create class called Bmw :
Polymorphism • Create two methods fuel_type and max_speed.
In Class methods Create objects from Ferrari and bmw, call methods.
output
Create class called Person :
• Create method introduce
Example 2: • create subclass from Person called Teacher :
• Create method introduce
Polymorphism create subclass from Person called Student :
with inheritance • Create method introduce
(method create subclass from Person called Administrator :
overriding)
Create objects and call methods.
class Person:

def introduce(self):
print("Hello, I'm a person")

class Teacher(Person):
def introduce(self):
print("Hello, I'm a teacher")

class Student(Person):
def introduce(self):
print("Hello, I'm a student")

class Administrator(Person):
pass

person = Person()
teacher = Teacher()
student = Student()
administrator = Administrator()
person.introduce() # Output: Hello, I'm a person
teacher.introduce() # Output: Hello, I'm a teacher
student.introduce() # Output: Hello, I'm a student
administrator.introduce() # Output: Hello, I'm a person

output
Create class called Vehicle :
• Two variables model and year.
Example 3: • Create two methods show and start_engine.
• create subclass from Vehicle called Car :
Polymorphism • Create two methods show and start_engine.

with inheritance create subclass from Vehicle called Bike:


• Create two methods show and start_engine.
(method
create subclass from Vehicle called Truck:
overriding) • Create two methods show and start_engine.
Create objects and call methods.
class Vehicle:

def __init__(self , model , year):


self.model = model
self.year = year

def show(self):
print(f"vehicle details: {self.model} {self.year}" )

def start_engine(self):
print("Starting engine...")

class Car(Vehicle):

def show(self):
print(f"car details: {self.model} {self.year}" )

def start_engine(self):
print("Starting car engine...")
class Bike(Vehicle):

def show(self):
print(f"vehicle details: {self.model} {self.year}" )

def start_engine(self):
print("Starting bike engine...")

class Truck(Vehicle):

def show(self):
print(f"truck details: {self.model} {self.year}")

def start_engine(self):
print("Starting truck engine...")

car = Car('bmw' , 2019)


bike = Bike('honda' , 2020)
truck = Truck('volvo' , 2018)
car.start_engine() # Output: Starting engine... Starting car engine...
car.show()
bike.start_engine() # Output: Starting engine... Starting bike engine...
bike.show()
truck.start_engine() # Output: Starting engine...
truck.show()

output

You might also like