Python Programming - Polymorphism

Exercise : Polymorphism - General Questions
  • Polymorphism - General Questions
21.
What is the purpose of the __str__() method in Python classes in the context of polymorphism?
To define class attributes
To create a new instance of the class
To represent the object as a string for display purposes
To access superclass attributes directly
Answer: Option
Explanation:
The __str__() method is used to represent the object as a string for display purposes, providing a human-readable representation.

22.
Which of the following is an example of polymorphism through method overloading?
Defining a method with the same name but different parameters in a class
Defining a method with the same name but different return types in a class
Defining a method with the same name in a class
Defining a method with different access modifiers in a class
Answer: Option
Explanation:
Polymorphism through method overloading in Python involves defining a method with the same name but different parameters in a class.

23.
Consider the following code:
class Animal:
    def speak(self):
        pass

class Duck(Animal):
    def speak(self):
        return "Quack!"

class Cow(Animal):
    def speak(self):
        return "Moo!"
What concept is demonstrated in this code?
Method overloading
Method overriding
Operator overloading
Polymorphism
Answer: Option
Explanation:
This code demonstrates method overriding, where the subclasses provide specific implementations for a method defined in the superclass.

24.
What is the purpose of the __len__() method in Python classes in the context of polymorphism?
To define class attributes
To customize the behavior when the len() function is called on an instance
To access superclass attributes directly
To create a new instance of the class
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.

25.
In Python, what is method overloading?
Defining multiple methods with the same name but different parameters in a class
Defining a method with the same name but different return types in a class
Overriding a method in a subclass with the same name as in the superclass
Defining a method with the same name in a class
Answer: Option
Explanation:
Method overloading in Python involves defining multiple methods with the same name but different parameters in a class.