Polymorphism
Polymorphism
For example, Jessa acts as an employee when she is at the office. However,
when she is at home, she acts like a wife. Also, she represents herself differently
in different places. Therefore, the same person takes different forms as per the
situation.
Example:
# calculate count
print(len(students))
print(len(school))
Output
10
3. The existing class is called a base class or parent class, and the new class is
called a subclass or child class or derived class.
In polymorphism, Python first checks the object’s class type and executes
the appropriate method when we call the method.
In this example, we have a vehicle class as a parent and a ‘Car’ and ‘Truck’
as its sub-class. But each vehicle can have a different seating capacity, speed, etc.,
so we can have the same instance method name in each class but with a different
implementation. Using this code can be extended and easily maintained over
time.
self.name = name
self.color = color
self.price = price
def show(self):
def max_speed(self):
def change_gear(self):
class Car(Vehicle):
def max_speed(self):
# Car Object
car.show()
car.max_speed()
car.change_gear()
# Vehicle Object
vehicle.show()
vehicle.max_speed()
vehicle.change_gear()
Output:
def fuel_type(self):
print("Petrol")
def max_speed(self):
class BMW:
def fuel_type(self):
print("Diesel")
def max_speed(self):
ferrari = Ferrari()
bmw = BMW()
car.fuel_type()
car.max_speed()
Output
Petrol
Diesel