Exercise: Python

Questions for: Polymorphism

What is the purpose of the __str__() method in Python classes?
A:
To define class attributes
B:
To customize the behavior when an instance is subtracted from another instance
C:
To represent the object as a string for display purposes
D:
To create a new instance of the class
Answer: C
The __str__() method is used to provide a human-readable string representation of an object for display purposes.
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))
A:
Drawing a shape
B:
Drawing a circle\nDrawing a square
C:
Drawing a square\nDrawing a circle
D:
Drawing a circle\nDrawing a circle
Answer: B
The display_shape_info() function calls the draw() method of the given shape, resulting in the specific drawing for each shape.
What is the purpose of the __eq__() method in Python classes in the context of polymorphism?
A:
To customize the behavior when an instance is checked for equality using the == operator
B:
To create a new instance of the class
C:
To define class attributes
D:
To customize the behavior when an item is accessed using square brackets on an instance
Answer: A
The __eq__() method is used to customize the behavior when an instance is checked for equality using the == operator, allowing for polymorphic behavior.
Which of the following is an example of polymorphism through "operator overloading"?
A:
Using the + operator to concatenate strings
B:
Using the + operator to add two numbers
C:
Using the + operator to access a list element
D:
Using the + operator to define a custom behavior in a class
Answer: D
Polymorphism through operator overloading in Python involves defining custom behavior for operators in a class, such as using __add__() for the + operator.
How does Python achieve polymorphism through "method overloading"?
A:
By allowing a function to take different types of arguments
B:
By automatically resolving conflicts using the first defined method
C:
By using the C3 linearization algorithm to determine method resolution order
D:
By allowing a function to be defined with the same name but different parameters
Answer: D
Polymorphism through method overloading in Python involves allowing a function to be defined with the same name but different parameters.
Ad Slot (Above Pagination)
Quiz