0
0
Pythonprogramming~10 mins

Method overriding behavior 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 override the method greet in the subclass.

Python
class Parent:
    def greet(self):
        return "Hello from Parent"

class Child(Parent):
    def greet(self):
        return [1]
Drag options to blanks, or click blank then click option'
Agreet()
Bsuper().greet()
C"Hello from Parent"
D"Hello from Child"
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the parent's greet method call instead of a new string.
Calling greet() without self or super().
2fill in blank
medium

Complete the code to call the parent class method greet inside the overridden method.

Python
class Parent:
    def greet(self):
        return "Hello from Parent"

class Child(Parent):
    def greet(self):
        return [1] + " and Child"
Drag options to blanks, or click blank then click option'
Asuper().greet()
B"Hello from Child"
CParent.greet()
Dself.greet()
Attempts:
3 left
💡 Hint
Common Mistakes
Calling self.greet() causes infinite recursion.
Calling Parent.greet() without passing self.
3fill in blank
hard

Fix the error in the overridden method to correctly call the parent class method.

Python
class Parent:
    def greet(self):
        return "Hello from Parent"

class Child(Parent):
    def greet(self):
        return Parent.greet([1]) + " and Child"
Drag options to blanks, or click blank then click option'
Aself
BChild
Csuper()
Dcls
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the class name instead of the instance.
Using super() inside a direct class method call.
4fill in blank
hard

Fill both blanks to override describe method and call the parent method inside it.

Python
class Animal:
    def describe(self):
        return "I am an animal"

class Dog(Animal):
    def describe(self):
        return [1] + ", and I am a dog"

obj = Dog()
print(obj.describe())
Drag options to blanks, or click blank then click option'
Asuper().describe()
BAnimal.describe(self)
C"I am an animal"
Dself.describe()
Attempts:
3 left
💡 Hint
Common Mistakes
Calling self.describe() causes infinite recursion.
Returning only the dog's string without calling parent.
5fill in blank
hard

Fill all three blanks to override info method, call parent method, and add extra info.

Python
class Vehicle:
    def info(self):
        return "Vehicle info"

class Car(Vehicle):
    def info(self):
        return [1] + ", model: " + [2] + ", year: " + [3]

car = Car()
print(car.info())
Drag options to blanks, or click blank then click option'
Asuper().info()
B"Model X"
C"2024"
Dself.info()
Attempts:
3 left
💡 Hint
Common Mistakes
Calling self.info() causes infinite recursion.
Not calling the parent method at all.