Professional Documents
Culture Documents
Section 7 - Polymorphism
Section 7 - Polymorphism
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.
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...")
output