Exercise: Polymorphism

Questions for: Polymorphism

Which of the following is an example of polymorphism through function overloading?
A:
Defining a function with the same name but different parameters in a module
B:
Defining a function with the same name but different return types in a module
C:
Defining a function with the same name in a module
D:
Defining a function with different access modifiers in a module
Answer: A
Polymorphism through function overloading in Python involves defining a function with the same name but different parameters in a module.
Consider the following code:
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __eq__(self, other):
        return self.title == other.title and self.author == other.author
What concept is demonstrated in this code?
A:
Method overloading
B:
Operator overloading
C:
Method overriding
D:
Polymorphism
Answer: B
This code demonstrates operator overloading using the __eq__() method to customize the behavior of the equality operator (==) for instances of the class.
In Python, what is operator overloading?
A:
Defining multiple methods with the same name but different parameters in a class
B:
Overriding a method in a subclass with the same name as in the superclass
C:
Defining custom behavior for operators in a class
D:
Defining a method with the same name but different return types in a class
Answer: C
Operator overloading in Python involves defining custom behavior for operators in a class, such as using methods like __add__() for the + operator.
How is polymorphism related to the concept of "duck typing"?
A:
Polymorphism in Python is based on the idea of explicitly specifying data types
B:
"Duck typing" refers to the ability of objects to take on multiple forms, which is a form of polymorphism
C:
Polymorphism in Python is achieved through static typing
D:
"Duck typing" refers to the use of explicit type declarations in Python
Answer: B
"Duck typing" in Python refers to the ability of objects to take on multiple forms or types based on their behavior, aligning with the concept of polymorphism.
Consider the following code:
class Animal:
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Woof!"

class Cat(Animal):
    def sound(self):
        return "Meow!"
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.
Ad Slot (Above Pagination)
Quiz