What is polymorphism in Python?
A
A way to define multiple constructors
B
A technique to define private methods
C
The ability to use a common interface for different data types or classes
D
Using many classes in a program
Analysis & Theory
Polymorphism allows the same interface to be used for different types of objects.
Which of the following demonstrates polymorphism?
A
Using `len()` on a list and a string
B
Using `for` loop on a range
C
Assigning one variable to another
D
Defining a class with `__init__`
Analysis & Theory
`len()` works on multiple data types like list, string, etc., demonstrating polymorphism.
What will this print?
class Cat:
def sound(self):
return 'Meow'
class Dog:
def sound(self):
return 'Bark'
def make_sound(animal):
print(animal.sound())
make_sound(Cat())
make_sound(Dog())
Analysis & Theory
`make_sound` calls the `sound()` method on different objects showing polymorphism.
Which of the following functions is an example of built-in polymorphism?
Analysis & Theory
`print()` can take many data types — string, int, list, etc. — and behaves accordingly.
Can method overriding be used to achieve polymorphism?
D
Only in functional programming
Analysis & Theory
Overriding allows different classes to define the same method in different ways.
What is method overriding in Python?
A
Using a method inside a loop
B
Redefining a method in the same class
C
Redefining a parent class method in a child class
D
Copying methods from one class to another
Analysis & Theory
Method overriding is when a child class redefines a method already defined in its parent class.
Which concept allows one function name to perform different tasks based on the object?
Analysis & Theory
Polymorphism enables the same function to behave differently depending on the object.
What happens if you call a method not defined in a class?
B
Python tries a similar method
C
Raises an AttributeError
D
Creates a default method
Analysis & Theory
If the method doesn’t exist, Python raises an `AttributeError`.
What is the output?
class A:
def greet(self):
print('Hi from A')
class B(A):
def greet(self):
print('Hi from B')
obj = B()
obj.greet()
Analysis & Theory
The child class B overrides the `greet()` method, so it prints 'Hi from B'.
Which type of polymorphism does Python support?
Analysis & Theory
Python supports run-time polymorphism using dynamic typing and method overriding.