Python Programming - Polymorphism

Exercise : Polymorphism - General Questions
  • Polymorphism - General Questions
76.
How does Python achieve polymorphism through "operator overloading"?
By explicitly specifying data types for objects
By allowing objects to take on multiple forms based on their behavior
By defining custom behavior for operators in a class
By using static typing to enforce object compatibility
Answer: Option
Explanation:
Python achieves polymorphism through operator overloading by allowing the definition of custom behavior for operators in a class, such as using methods like __add__() for the + operator.

77.
Which of the following is an example of polymorphism through "function overriding"?
Defining a function with the same name but different parameters in a module
Defining a function with different access modifiers in a module
Defining a function with the same name in a module
Defining a function with the same name but different return types in a module
Answer: Option
Explanation:
Polymorphism through function overriding in Python involves defining a function with the same name in a module, where a subclass provides a specific implementation for the function.

78.
What is the output of the following Python code?
class Animal:
    def make_sound(self):
        return "Generic animal sound"

class Dog(Animal):
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

def pet_sounds(animals):
    for animal in animals:
        print(animal.make_sound())

dog = Dog()
cat = Cat()

pet_sounds([dog, cat])
Generic animal sound\nWoof!\nMeow!
Woof!\nMeow!\nGeneric animal sound
Woof!\nMeow!\nMeow!
Generic animal sound\nGeneric animal sound\nGeneric animal sound
Answer: Option
Explanation:
The pet_sounds() function demonstrates polymorphism, printing different sounds based on the specific implementations of the make_sound() method in the Dog and Cat classes.