Exercise: Polymorphism
Questions for: Polymorphism
What is the purpose of the
__add__() method in Python classes in the context of polymorphism?
A:
To define class attributes
B:
To customize the behavior when an instance is added to 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
__add__() method is used to customize the behavior when an instance is added to another instance, allowing for polymorphic behavior.
How does Python achieve polymorphism through method overriding?
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 subclass to provide a specific implementation for a method defined in the superclass
Answer: D
Polymorphism through method overriding in Python allows a subclass to provide a specific implementation for a method defined in the superclass.
Discuss About this Question.
Consider the following code:
class Shape:
def area(self):
pass
class Circle(Shape):
def area(self, radius):
return 3.14 * radius * radius
class Rectangle(Shape):
def area(self, length, width):
return length * width
What concept is demonstrated in this code?
A:
Method overloading
B:
Method overriding
C:
Operator overloading
D:
Polymorphism
Answer: A
This code demonstrates method overloading, where the subclass methods have the same name but different parameters than the superclass method.
Discuss About this Question.
In Python, what is method overloading?
A:
Defining multiple methods with the same name but different parameters in a class
B:
Defining a method with the same name but different return types in a class
C:
Overriding a method in a subclass with the same name as in the superclass
D:
Defining a method with the same name in a class
Answer: A
Method overloading in Python involves defining multiple methods with the same name but different parameters in a class.
Discuss About this Question.
Consider the following code:
class Animal:
def speak(self):
pass
class Duck(Animal):
def speak(self):
return "Quack!"
class Cow(Animal):
def speak(self):
return "Moo!"
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.