Python Programming - Polymorphism

Exercise : Polymorphism - General Questions
  • Polymorphism - General Questions
71.
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.

72.
Which of the following is an example of polymorphism through "function overriding"?
Defining a function with the same name but different parameters in a module
Defining a function with different access modifiers in a module
Defining a function with the same name in a module
Defining a function with the same name but different return types in a module
Answer: Option
Explanation:
Polymorphism through function overriding in Python involves defining a function with the same name in a module, where a subclass provides a specific implementation for the function.

73.
What is the output of the following Python code?
class Shape:
    def draw(self):
        return "Drawing a shape"

class Circle(Shape):
    def draw(self):
        return "Drawing a circle"

class Square(Shape):
    def draw(self):
        return "Drawing a square"

def display_shape_info(shape):
    return shape.draw()

circle = Circle()
square = Square()

print(display_shape_info(circle))
print(display_shape_info(square))
Drawing a shape\nDrawing a shape
Drawing a circle\nDrawing a square
Drawing a square\nDrawing a circle
Drawing a circle\nDrawing a circle
Answer: Option
Explanation:
The display_shape_info() function calls the draw() method of the given shape, resulting in the specific drawing for each shape.

74.
In Python, what is the purpose of the __str__() method in the context of polymorphism?
To customize the behavior when an instance is checked for equality using the == operator
To represent the object as a string for display purposes
To define class attributes
To create a new instance of the class
Answer: Option
Explanation:
The __str__() method is used to provide a human-readable string representation of an object for display purposes.

75.
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?
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.