18
loading...
This website collects cookies to deliver better user experience
class Animal:
def __init__(self, name):
self.name = name
def get_name(self):
pass
def animal_sounds(animals):
for animal in animals:
if animal.name == "lion":
print("roar")
elif animal.name == "mouse":
print("squeak")
animals = [
Animal("lion"),
Animal("mouse")
]
animal_sounds(animals)
animals
array we need to modify the animal_sound() function. For every new animal, new logic needs to be added and the same change would be done at multiple places if our application becomes more complex, as is the case with actual projects.class Animal:
def __init__(self, name):
self.name = name
def get_name(self):
pass
def make_sound(self):
pass
class Lion(Animal):
def make_sound(self):
print("roar")
class Mouse(Animal):
def make_sound(self):
print("squeak")
class Cow(Animal):
def make_sound(self):
print("moo")
def animal_sounds(animals):
for animal in animals:
animal.make_sound()
animals = [
Lion(name="Big Cat"),
Mouse(name="Squeakie")
]
animal_sounds(animals)
make_sound
abstract function. Other animal classes (Lion, Mouse etc.) have extended the Animal class and implemented their own definition of make_sound function.