Python Polymorphism
Polymorphism in Python refers to the ability of different objects to be treated as instances of a common superclass. It allows methods to be defined in a way that they can operate on objects of different classes, enabling flexibility and dynamic behavior in code execution.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive",self.brand,self.model,"!")
class Boat:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Sail",self.brand,self.model,"!")
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Fly",self.brand,self.model,"!")
car1 = Car("Ford", "Mustang") # Creates an object of the Car class
boat1 = Boat("Ibiza", "Touring 20") # Creates an object of the Boat class
plane1 = Plane("Boeing", "747") # Creates an object of the Plane class
for x in (car1, boat1, plane1):
x.move()
Python Online Compiler