Python Programming - Polymorphism

Exercise : Polymorphism - General Questions
  • Polymorphism - General Questions
51.
How does Python achieve polymorphism through "method overloading"?
By allowing a function to take different types of arguments
By automatically resolving conflicts using the first defined method
By using the C3 linearization algorithm to determine method resolution order
By allowing a function to be defined with the same name but different parameters
Answer: Option
Explanation:
Polymorphism through method overloading in Python involves allowing a function to be defined with the same name but different parameters.

52.
Which of the following is an example of polymorphism through "operator overloading"?
Using the + operator to concatenate strings
Using the + operator to add two numbers
Using the + operator to access a list element
Using the + operator to define a custom behavior in a class
Answer: Option
Explanation:
Polymorphism through operator overloading in Python involves defining custom behavior for operators in a class, such as using __add__() for the + operator.

53.
What is the purpose of the __eq__() method in Python classes in the context of polymorphism?
To customize the behavior when an instance is checked for equality using the == operator
To create a new instance of the class
To define class attributes
To customize the behavior when an item is accessed using square brackets on an instance
Answer: Option
Explanation:
The __eq__() method is used to customize the behavior when an instance is checked for equality using the == operator, allowing for polymorphic behavior.

54.
What is the output of the following Python code?
class Shape:
    def draw(self):
        return "Drawing a shape"

class Circle(Shape):
    def draw(self):
        return "Drawing a circle"

class Square(Shape):
    def draw(self):
        return "Drawing a square"

def display_shape_info(shape):
    return shape.draw()

circle = Circle()
square = Square()

print(display_shape_info(circle))
print(display_shape_info(square))
Drawing a shape
Drawing a circle\nDrawing a square
Drawing a square\nDrawing a circle
Drawing a circle\nDrawing a circle
Answer: Option
Explanation:
The display_shape_info() function calls the draw() method of the given shape, resulting in the specific drawing for each shape.

55.
What is the purpose of the __str__() method in Python classes?
To define class attributes
To customize the behavior when an instance is subtracted from another instance
To represent the object as a string for display purposes
To create a new instance of the class
Answer: Option
Explanation:
The __str__() method is used to provide a human-readable string representation of an object for display purposes.