Exercise: Polymorphism

Questions for: Polymorphism

Consider the following Python code:
class Sports:
    def play(self):
        return "Generic sports activity"

class Football(Sports):
    def play(self):
        return "Playing football"

class Basketball(Sports):
    def play(self):
        return "Playing basketball"
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 __str__() method in the context of polymorphism?
A:
To customize the behavior when an instance is checked for equality using the == operator
B:
To represent the object as a string for display purposes
C:
To define class attributes
D:
To create a new instance of the class
Answer: B
The __str__() method is used to provide a human-readable string representation of an object for display purposes.
Consider the following code:
class Animal:
    def sound(self):
        return "Generic animal sound"

class Duck(Animal):
    def sound(self):
        return "Quack!"

class Lion(Animal):
    def sound(self):
        return "Roar!"
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 __call__() method in the context of polymorphism?
A:
To customize the behavior when an instance is checked for membership using the in keyword
B:
To customize the behavior when the instance is called as a function
C:
To define class attributes
D:
To create a new instance of the class
Answer: B
The __call__() method is used to customize the behavior when an instance is called as a function, allowing for polymorphic behavior.
What is the output of the following Python code?
class Vehicle:
    def start(self):
        return "Generic vehicle starting"

class Car(Vehicle):
    def start(self):
        return "Car starting"

class Bike(Vehicle):
    def start(self):
        return "Bike starting"

def drive(vehicle):
    return vehicle.start()

car = Car()
bike = Bike()

print(drive(car))
print(drive(bike))
A:
Generic vehicle starting\nCar starting
B:
Car starting\nBike starting
C:
Bike starting\nCar starting
D:
Car starting\nCar starting
Answer: B
The drive() function demonstrates polymorphism, accepting both Car and Bike instances and producing different outputs based on their specific implementations of the start() method.
Ad Slot (Above Pagination)
Quiz