Python Programming - Polymorphism

Exercise : Polymorphism - General Questions
  • Polymorphism - General Questions
26.
Consider the following code:
class Shape:
    def area(self):
        pass

class Circle(Shape):
    def area(self, radius):
        return 3.14 * radius * radius

class Rectangle(Shape):
    def area(self, length, width):
        return length * width
What concept is demonstrated in this code?
Method overloading
Method overriding
Operator overloading
Polymorphism
Answer: Option
Explanation:
This code demonstrates method overloading, where the subclass methods have the same name but different parameters than the superclass method.

27.
How does Python achieve polymorphism through method overriding?
By allowing a function to take different types of arguments
By automatically resolving conflicts using the first defined method
By using the C3 linearization algorithm to determine method resolution order
By allowing a subclass to provide a specific implementation for a method defined in the superclass
Answer: Option
Explanation:
Polymorphism through method overriding in Python allows a subclass to provide a specific implementation for a method defined in the superclass.

28.
What is the purpose of the __getitem__() method in Python classes in the context of polymorphism?
To define class attributes
To customize the behavior when an instance is deleted
To customize the behavior when an item is accessed using square brackets on an instance
To create a new instance of the class
Answer: Option
Explanation:
The __getitem__() method is used to customize the behavior when an item is accessed using square brackets on an instance, allowing for polymorphic behavior.

29.
Which of the following statements about polymorphism in Python is correct?
Polymorphism is achieved through operator overloading only
Polymorphism is achieved through method overriding only
Polymorphism is achieved through both method overloading and overriding
Polymorphism is achieved through operator overloading and method overloading
Answer: Option
Explanation:
Polymorphism in Python is achieved through both method overloading and method overriding.

30.
What is the purpose of the __add__() method in Python classes in the context of polymorphism?
To define class attributes
To customize the behavior when an instance is added to another instance
To customize the behavior when an item is accessed using square brackets on an instance
To create a new instance of the class
Answer: Option
Explanation:
The __add__() method is used to customize the behavior when an instance is added to another instance, allowing for polymorphic behavior.