ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Animal:
    sound = "..."
    def make_sound(self):
        return f"{type(self).__name__} says {self.sound}"
class Dog(Animal):
    sound = "Woof"
class Cat(Animal):
    sound = "Meow"
animals = [Dog(), Cat(), Animal()]
print([a.make_sound() for a in animals])
  1. A. ['Animal says Woof', 'Animal says Meow', 'Animal says ...']
  2. B. ['Dog says Woof', 'Cat says Meow', 'Animal says ...']
  3. C. ['Dog says ...', 'Cat says ...', 'Animal says ...']
  4. D. ['Dog says Woof', 'Cat says Meow', 'Animal says Woof']

Correct answer: B. ['Dog says Woof', 'Cat says Meow', 'Animal says ...']

type(self).__name__ reports each instance's ACTUAL class, and self.sound looks up the overridden class attribute for each subclass, so each object correctly reports its own name and sound.

More Python Programming questions

Exams that ask this topic