Introduction
Polymorphism lets different objects use the same action name but do different things. It helps write flexible and simple code.
Jump into concepts and practice - no test required
Polymorphism lets different objects use the same action name but do different things. It helps write flexible and simple code.
class ParentClass: def method(self): # common method pass class ChildClass(ParentClass): def method(self): # different behavior pass
Child classes override the method from the parent to change behavior.
Use the same method name in child classes for polymorphism.
class Animal: def sound(self): print("Some sound") class Dog(Animal): def sound(self): print("Bark") class Cat(Animal): def sound(self): print("Meow")
def make_sound(animal): animal.sound() make_sound(Dog()) # prints Bark make_sound(Cat()) # prints Meow
This program shows how different animals use the same method name but make different sounds.
class Animal: def sound(self): print("Some generic sound") class Dog(Animal): def sound(self): print("Bark") class Cat(Animal): def sound(self): print("Meow") animals = [Dog(), Cat(), Animal()] for animal in animals: animal.sound()
Polymorphism helps avoid many if-else checks for object types.
Always use the same method name in parent and child classes for polymorphism to work.
Polymorphism means one method name, many behaviors.
It works by overriding methods in child classes.
It makes code easier to extend and maintain.
override keyword; renaming is not overriding; calling parent method alone is not overriding.override keywordclass Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
animals = [Dog(), Cat(), Animal()]
for a in animals:
print(a.sound())sound method to return "Bark" and "Meow" respectively.sound() on Dog(), Cat(), and Animal() objects, printing "Bark", "Meow", and "Some sound".class Vehicle:
def move(self):
print("Moving")
class Car(Vehicle):
def move(self):
print("Driving")
class Bike(Vehicle):
def move(self):
print("Riding")
vehicles = [Car(), Bike()]
for v in vehicles:
v.movev.move without parentheses, so method is not called.move method -> Option DBird that also uses polymorphism with sound(). Which code correctly extends the existing classes and uses polymorphism?sound() method to maintain polymorphism.sound() works correctly.