Exercise: Polymorphism
Questions for: Polymorphism
In Python, what is the purpose of the
__contains__() method?
A:
To define class attributes
B:
To customize the behavior when an item is checked for membership using the
in keyword
C:
To create a new instance of the class
D:
To customize the behavior when an instance is compared using the
== operator
Answer: B
The
__contains__() method is used to customize the behavior when an item is checked for membership using the in keyword, allowing for polymorphic behavior.
What is the purpose of the
__floordiv__() method in Python classes in the context of polymorphism?
A:
To customize the behavior when an instance is divided using floor division by 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
__floordiv__() method is used to customize the behavior when an instance is divided using floor division by another instance, allowing for polymorphic behavior.Discuss About this Question.
Which of the following is an example of polymorphism through function overriding?
A:
Defining a function with the same name but different parameters in a module
B:
Defining a function with the same name but different return types in a module
C:
Defining a function with the same name in a module
D:
Defining a function with different access modifiers in a module
Answer: C
Polymorphism through function overriding in Python involves defining a function with the same name in a module, where a subclass provides a specific implementation for the function.
Discuss About this Question.
How does Python achieve polymorphism through "parametric polymorphism"?
A:
By explicitly specifying data types for objects
B:
By using static typing to enforce object compatibility
C:
By allowing objects to take on multiple forms based on their behavior
D:
By 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.
Discuss About this Question.
Consider the following code:
class Guitar:
def play(self):
pass
class ElectricGuitar(Guitar):
def play(self):
return "Distorted sound!"
class AcousticGuitar(Guitar):
def play(self):
return "Harmonious sound!"
What concept is demonstrated in this code?
A:
Method overloading
B:
Method overriding
C:
Operator overloading
D:
Polymorphism
Answer: B
This code demonstrates method overriding, where the subclasses provide specific implementations for a method defined in the superclass.
Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.