Exercise: Polymorphism
Questions for: Polymorphism
Consider the following code:
class Shape:
def draw(self):
return "Drawing a shape"
class Triangle(Shape):
def draw(self):
return "Drawing a triangle"
class Rectangle(Shape):
def draw(self):
return "Drawing a rectangle"
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.
In Python, what is the purpose of the
__getitem__() method in the context of polymorphism?
A:
To define class attributes
B:
To customize the behavior when an item is checked for membership using the
in keyword
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: C
The
__getitem__() method is used to customize the behavior when an item is accessed using square brackets on an instance of the class, allowing for polymorphic behavior.Discuss About this Question.
What is the output of the following Python code?
class Animal:
def make_sound(self):
return "Generic animal sound"
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
def pet_sounds(animals):
for animal in animals:
print(animal.make_sound())
dog = Dog()
cat = Cat()
pet_sounds([dog, cat])
A:
Generic animal sound\nWoof!\nMeow!
B:
Woof!\nMeow!
C:
Woof!\nMeow!\nMeow!
D:
Generic animal sound\nGeneric animal sound\nGeneric animal sound
Answer: B
The
pet_sounds() function demonstrates polymorphism, printing different sounds based on the specific implementations of the make_sound() method in the Dog and Cat classes.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 different access modifiers in a module
C:
Defining a function with the same name in a module
D:
Defining a function with the same name but different return types 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 "operator overloading"?
A:
By explicitly specifying data types for objects
B:
By allowing objects to take on multiple forms based on their behavior
C:
By defining custom behavior for operators in a class
D:
By using static typing to enforce object compatibility
Answer: C
Python achieves polymorphism through operator overloading by allowing the definition of custom behavior for operators in a class, such as using methods like
__add__() for the + operator.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.