Introduction
Polymorphism lets us use the same action in different ways for different things. It helps make code simple and flexible.
Jump into concepts and practice - no test required
Polymorphism lets us use the same action in different ways for different things. It helps make code simple and flexible.
class Animal: def sound(self): pass class Dog(Animal): def sound(self): print("Bark") class Cat(Animal): def sound(self): print("Meow") animals = [Dog(), Cat()] for animal in animals: animal.sound()
Polymorphism often uses methods with the same name in different classes.
It works well with inheritance but can also be used with other techniques.
class Bird: def fly(self): print("Bird is flying") class Airplane: def fly(self): print("Airplane is flying") for thing in [Bird(), Airplane()]: thing.fly()
def add(x, y): return x + y print(add(2, 3)) print(add('Hi, ', 'there!'))
Both Square and Circle have an area method. We call area on each shape without caring about its type.
class Shape: def area(self): pass class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side * self.side class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius * self.radius shapes = [Square(4), Circle(3)] for shape in shapes: print(f"Area: {shape.area()}")
Polymorphism helps avoid long if-else or switch statements checking types.
It makes code easier to extend and maintain.
Polymorphism means one action can work in different ways.
It helps write flexible and simple code.
It is often used with classes and methods sharing the same name.
polymorphism in Python programming?class Dog:
def sound(self):
return "Bark"
class Cat:
def sound(self):
return "Meow"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.sound())class Bird:
def fly(self):
print("Flying")
class Penguin(Bird):
def fly(self):
print("Cannot fly")
p = Penguin()
p.fly()draw() method, regardless of the object's class. Which concept does this best illustrate?