Exercise: Polymorphism
Questions for: Polymorphism
Which of the following is an example of polymorphism through method overloading?
A:
Defining a method 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:
Defining a method with the same name in a class
D:
Defining a method with different access modifiers in a class
Answer: A
Polymorphism through method overloading in Python involves defining a method with the same name but different parameters in a class.
What is the purpose of the
__str__() method in Python classes in the context of polymorphism?
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 access superclass attributes directly
Answer: C
The
__str__() method is used to represent the object as a string for display purposes, providing a human-readable representation.Discuss About this Question.
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.Discuss About this Question.
What is the purpose of the
__call__() method in Python classes in the context of polymorphism?
A:
To create a new instance of the class
B:
To customize the behavior when an instance is called as a function
C:
To customize the behavior when an instance is deleted
D:
To access superclass attributes directly
Answer: B
The
__call__() method is used to customize the behavior when an instance is called as a function, allowing for polymorphic behavior.Discuss About this Question.
Consider the following code:
class Shape:
def area(self):
pass
class Triangle(Shape):
def area(self, base, height):
return 0.5 * base * height
class Square(Shape):
def area(self, side):
return side * side
What concept is demonstrated in this code?
A:
Operator overloading
B:
Method overloading
C:
Method overriding
D:
Polymorphism
Answer: B
This code demonstrates method overloading, where the subclass methods have the same name but different parameters than the superclass method.
Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.