Python Programming - Polymorphism
Exercise : Polymorphism - General Questions
- Polymorphism - General Questions
56.
What does the following Python code demonstrate?
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def pet_sound(animal):
return animal.speak()
dog = Dog()
cat = Cat()
print(pet_sound(dog))
print(pet_sound(cat))
Answer: Option
Explanation:
The
pet_sound()
function demonstrates polymorphism as it can accept different types of animals (instances of Dog and Cat) and produce different sounds based on their specific implementations.
57.
What is the output of the following Python code?
class Car:
def start(self):
return "Car starting"
class ElectricCar(Car):
def start(self):
return "Electric car starting"
def drive(car):
return car.start()
car = Car()
electric_car = ElectricCar()
print(drive(car))
print(drive(electric_car))
Answer: Option
Explanation:
The
drive()
function demonstrates polymorphism, accepting both Car and ElectricCar instances and producing different outputs based on their specific implementations of the start()
method.
58.
Consider the following Python code:
class Bird:
def fly(self):
return "Bird flying"
class Penguin(Bird):
def fly(self):
return "Penguin can't fly"
def display_flying_ability(bird):
return bird.fly()
bird = Bird()
penguin = Penguin()
print(display_flying_ability(bird))
print(display_flying_ability(penguin))
Answer: Option
Explanation:
The
display_flying_ability()
function demonstrates polymorphism, accepting both Bird and Penguin instances and producing different outputs based on their specific implementations of the fly()
method.
59.
In Python, what is the purpose of the
__len__()
method in the context of polymorphism?
Answer: Option
Explanation:
The
__len__()
method is used to customize the behavior when the len()
function is called on an instance of the class, allowing for polymorphic behavior.
60.
Consider the following code:
class MusicInstrument:
def play(self):
return "Playing music instrument"
class Guitar(MusicInstrument):
def play(self):
return "Strumming the guitar"
class Piano(MusicInstrument):
def play(self):
return "Playing the piano"
What concept is demonstrated in this code?
Answer: Option
Explanation:
This code demonstrates method overriding, where the subclasses provide specific implementations for a method defined in the superclass.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers