Python Programming - Polymorphism

Exercise : Polymorphism - General Questions
  • Polymorphism - General Questions
36.
Consider the following code:
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __eq__(self, other):
        return self.title == other.title and self.author == other.author
What concept is demonstrated in this code?
Method overloading
Operator overloading
Method overriding
Polymorphism
Answer: Option
Explanation:
This code demonstrates operator overloading using the __eq__() method to customize the behavior of the equality operator (==) for instances of the class.

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

38.
What is the purpose of the __sub__() method in Python classes in the context of polymorphism?
To customize the behavior when an instance is subtracted from another instance
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 __sub__() method is used to customize the behavior when an instance is subtracted from another instance, allowing for polymorphic behavior.

39.
In Python, what is the purpose of the __str__() method?
To define class attributes
To create a new instance of the class
To represent the object as a string for display purposes
To customize the behavior when an item is accessed using square brackets on an instance
Answer: Option
Explanation:
The __str__() method is used to represent the object as a string for display purposes, providing a human-readable representation.

40.
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?
Operator overloading
Method overloading
Method overriding
Polymorphism
Answer: Option
Explanation:
This code demonstrates operator overloading using the __sub__() method to customize the behavior of the subtraction operator (-) for instances of the class.