0
0
Pythonprogramming~20 mins

Purpose of inheritance in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Inheritance Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this inheritance example?
Look at the code below. What will it print when run?
Python
class Animal:
    def speak(self):
        return "I make a sound"

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

pet = Dog()
print(pet.speak())
AAttributeError
BI make a sound
CTypeError
DWoof!
Attempts:
2 left
💡 Hint
Remember, the Dog class changes the speak method.
🧠 Conceptual
intermediate
1:30remaining
Why use inheritance in programming?
Which of these is the main purpose of inheritance?
ATo reuse code and create a relationship between classes
BTo make programs run faster
CTo hide all data from users
DTo prevent any changes to code
Attempts:
2 left
💡 Hint
Think about how inheritance helps avoid repeating code.
Predict Output
advanced
2:00remaining
What is the output of this multi-level inheritance?
What will this code print?
Python
class A:
    def greet(self):
        return "Hello from A"

class B(A):
    def greet(self):
        return "Hello from B"

class C(B):
    pass

obj = C()
print(obj.greet())
AHello from B
BHello from A
CAttributeError
DTypeError
Attempts:
2 left
💡 Hint
Check which class defines greet and which classes inherit it.
🔧 Debug
advanced
2:00remaining
Which option causes an error in inheritance?
Which code snippet will cause an error when run?
A
class Parent:
    def greet(self):
        return "Hi"
class Child(Parent):
    def greet(self):
        return super().greet() + " there"
obj = Child()
print(obj.greet())
B
class Parent:
    def __init__(self):
        self.value = 5
class Child(Parent):
    def __init__(self):
        super().__init__()
        self.value = 10
obj = Child()
print(obj.value)
C
class Parent:
    def __init__(self):
        self.value = 5
class Child(Parent):
    def __init__(self):
        pass
obj = Child()
print(obj.value)
D
class Parent:
    pass
class Child(Parent):
    pass
obj = Child()
Attempts:
2 left
💡 Hint
Look at how the Child class initializes value and if it calls the Parent constructor.
🧠 Conceptual
expert
1:30remaining
What is the main benefit of method overriding in inheritance?
Why do programmers override methods in child classes?
ATo prevent the parent class method from running ever
BTo change or extend the behavior of a method from the parent class
CTo make the program run slower for debugging
DTo copy the parent method exactly without changes
Attempts:
2 left
💡 Hint
Think about how child classes customize behavior.