What is the main purpose of polymorphism in programming?
Think about how different objects can share the same interface or method names.
Polymorphism allows different classes to be accessed through the same interface, enabling flexible and reusable code.
What is the output of this Python code demonstrating polymorphism?
class Animal: def sound(self): return "Some sound" class Dog(Animal): def sound(self): return "Bark" class Cat(Animal): def sound(self): return "Meow" animals = [Dog(), Cat(), Animal()] for animal in animals: print(animal.sound())
Each subclass overrides the sound method.
The Dog and Cat classes override the sound method of Animal. When called, the method of the actual object type runs.
What error will this code produce related to polymorphism?
class Bird: def fly(self): print("Flying") class Penguin(Bird): pass p = Penguin() p.fly()
Check if Penguin inherits the method from Bird.
Penguin inherits from Bird, so it has the fly method. Calling p.fly() prints 'Flying' without error.
Which option correctly defines a polymorphic method area in two classes?
class Shape: def area(self): pass class Square(Shape): def __init__(self, side): self.side = side # Define area method here class Circle(Shape): def __init__(self, radius): self.radius = radius # Define area method here
Remember to use self to access instance variables.
Methods must include self and use it to access instance variables. The formulas must be correct for area.
What will be the output of this code that uses polymorphism in function arguments?
class Printer: def print_message(self): print("Generic message") class EmailPrinter(Printer): def print_message(self): print("Email message") class SMSPrinter(Printer): def print_message(self): print("SMS message") def send_notification(printer: Printer): printer.print_message() send_notification(EmailPrinter()) send_notification(SMSPrinter()) send_notification(Printer())
Each subclass overrides print_message. The function calls the method on the passed object.
The function send_notification calls print_message on the object passed. Polymorphism ensures the correct method runs based on the object's class.