Exercise: Polymorphism

Questions for: Polymorphism

Which of the following is an example of operator overloading?
A:
Defining a method with the same name in a class
B:
Defining a method with the same name but different parameters in a class
C:
Defining a method with the same name but different return types in a class
D:
Defining the __add__() method in a class
Answer: D
Operator overloading in Python involves defining methods like __add__() to provide custom behavior for operators.
What is dynamic polymorphism?
A:
The ability of a function to take different types of arguments
B:
The ability of a class to inherit from multiple classes
C:
The ability of an object to take on multiple forms or types at runtime
D:
The ability to define custom behavior for operators in a class
Answer: C
Dynamic polymorphism in Python refers to the ability of an object to take on multiple forms or types at runtime, often achieved through method overriding.
What is the purpose of the __iter__() 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 deleted
C:
To customize the behavior when the iter() function is called on an instance
D:
To access superclass attributes directly
Answer: C
The __iter__() method is used to customize the behavior when the iter() function is called on an instance of the class, allowing for polymorphic behavior.
How is polymorphism different from encapsulation?
A:
Polymorphism is the ability to hide implementation details, while encapsulation is the ability of an object to take on multiple forms.
B:
Polymorphism is the ability to define custom behavior for operators, while encapsulation is the bundling of data and methods that operate on the data.
C:
Polymorphism is the ability of a function to take different types of arguments, while encapsulation is the ability to represent data and the methods that operate on the data within a single unit.
D:
Polymorphism is the ability of an object to take on multiple forms or types, while encapsulation is the ability to restrict access to certain details of an object and only expose what is necessary.
Answer: D
Polymorphism is about the ability of objects to take on multiple forms or types, while encapsulation is about bundling data and methods within a single unit and controlling access to details.
Consider the following code:
class Animal:
    def speak(self):
        pass

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

class Cat(Animal):
    def speak(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