Exercise: Polymorphism

Questions for: Polymorphism

What is the purpose of the __mul__() method in Python classes in the context of polymorphism?
A:
To define class attributes
B:
To customize the behavior when an instance is multiplied by another instance
C:
To customize the behavior when an item is accessed using square brackets on an instance
D:
To create a new instance of the class
Answer: B
The __mul__() method is used to customize the behavior when an instance is multiplied by another instance, allowing for polymorphic behavior.
How is polymorphism related to the concept of "parametric polymorphism"?
A:
Polymorphism in Python is based on explicit type declarations
B:
"Parametric polymorphism" refers to the ability of objects to take on multiple forms, which is a form of polymorphism
C:
Polymorphism in Python is achieved through static typing
D:
"Parametric polymorphism" refers to defining functions or classes that can operate on different data types
Answer: D
"Parametric polymorphism" in Python refers to defining functions or classes that can operate on different data types, contributing to polymorphic behavior.
Consider the following code:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)
What concept is demonstrated in this code?
A:
Operator overloading
B:
Method overloading
C:
Method overriding
D:
Polymorphism
Answer: A
This code demonstrates operator overloading using the __sub__() method to customize the behavior of the subtraction operator (-) for instances of the class.
In Python, what is the purpose of the __str__() method?
A:
To define class attributes
B:
To create a new instance of the class
C:
To represent the object as a string for display purposes
D:
To customize the behavior when an item is accessed using square brackets on an instance
Answer: C
The __str__() method is used to represent the object as a string for display purposes, providing a human-readable representation.
What is the purpose of the __sub__() method in Python classes in the context of polymorphism?
A:
To customize the behavior when an instance is subtracted from another instance
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 __sub__() method is used to customize the behavior when an instance is subtracted from another instance, allowing for polymorphic behavior.
Ad Slot (Above Pagination)
Quiz