0
0
Pythonprogramming~10 mins

Polymorphism through inheritance in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a method that prints a greeting.

Python
class Animal:
    def speak(self):
        print([1])

pet = Animal()
pet.speak()
Drag options to blanks, or click blank then click option'
AHello
B"Hello!"
Cprint("Hello!")
Dreturn "Hello!"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string.
Using return instead of print.
Trying to print inside the print statement.
2fill in blank
medium

Complete the code to override the speak method in the Dog class.

Python
class Animal:
    def speak(self):
        print("Some sound")

class Dog(Animal):
    def speak(self):
        print([1])

pet = Dog()
pet.speak()
Drag options to blanks, or click blank then click option'
Areturn "Woof!"
BWoof!
Cprint("Woof!")
D"Woof!"
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes around the string.
Using print inside print.
Using return instead of print.
3fill in blank
hard

Fix the error in the code to call the speak method of the Cat class.

Python
class Animal:
    def speak(self):
        print("Some sound")

class Cat(Animal):
    def speak(self):
        print("Meow!")

pet = Cat()
pet.[1]()
Drag options to blanks, or click blank then click option'
Aspeak
Bsay
Csound
Dtalk
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names not defined in the class.
Forgetting parentheses when calling the method.
4fill in blank
hard

Fill both blanks to create a list of animals and call their speak methods.

Python
class Animal:
    def speak(self):
        print("Some sound")

class Bird(Animal):
    def speak(self):
        print("Chirp!")

animals = [[1], [2]]
for pet in animals:
    pet.speak()
Drag options to blanks, or click blank then click option'
AAnimal()
BBird()
CDog()
DCat()
Attempts:
3 left
💡 Hint
Common Mistakes
Using class names without parentheses.
Using classes not defined in the code.
5fill in blank
hard

Fill both blanks to create a dictionary mapping animal names to their sounds using polymorphism.

Python
class Animal:
    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

pets = [Dog(), Cat()]
sounds = { = {pet.{BLANK_2}}(): pet.{{BLANK_2}}() for pet in pets}
Drag options to blanks, or click blank then click option'
A{
Bspeak
D[
Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets instead of curly braces for dictionary.
Not calling the method with parentheses.
Using different method names.