Python Programming - Polymorphism

Exercise : Polymorphism - General Questions
  • Polymorphism - General Questions
66.
How does Python achieve polymorphism through "method overloading"?
By explicitly specifying data types for objects
By automatically resolving conflicts using the first defined method
By using the C3 linearization algorithm to determine method resolution order
By allowing a function to be defined with the same name but different parameters
Answer: Option
Explanation:
Polymorphism through method overloading in Python involves allowing a function to be defined with the same name but different parameters.

67.
Which of the following is an example of polymorphism through "operator overloading"?
Using the + operator to concatenate strings
Using the + operator to add two numbers
Using the + operator to access a list element
Using the + operator to define a custom behavior in a class
Answer: Option
Explanation:
Polymorphism through operator overloading in Python involves defining custom behavior for operators in a class, such as using __add__() for the + operator.

68.
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))
Generic vehicle starting\nCar starting
Car starting\nBike starting
Bike starting\nCar starting
Car starting\nCar starting
Answer: Option
Explanation:
The drive() function demonstrates polymorphism, accepting both Car and Bike instances and producing different outputs based on their specific implementations of the start() method.

69.
In Python, what is the purpose of the __call__() method in the context of polymorphism?
To customize the behavior when an instance is checked for membership using the in keyword
To customize the behavior when the instance is called as a function
To define class attributes
To create a new instance of the class
Answer: Option
Explanation:
The __call__() method is used to customize the behavior when an instance is called as a function, allowing for polymorphic behavior.

70.
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?
Method overloading
Method overriding
Operator overloading
Polymorphism
Answer: Option
Explanation:
This code demonstrates method overriding, where the subclasses provide specific implementations for a method defined in the superclass.