0
0
Pythonprogramming~20 mins

Method overriding behavior in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Method Overriding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of method overriding with super()
What is the output of this Python code?
Python
class Parent:
    def greet(self):
        return "Hello from Parent"

class Child(Parent):
    def greet(self):
        return super().greet() + " and Child"

obj = Child()
print(obj.greet())
ATypeError
BHello from Parent
Cand Child
DHello from Parent and Child
Attempts:
2 left
💡 Hint
Think about how super() calls the parent method and how the returned string is combined.
Predict Output
intermediate
2:00remaining
Output when overriding without calling super()
What will this code print?
Python
class Base:
    def message(self):
        return "Base message"

class Derived(Base):
    def message(self):
        return "Derived message"

obj = Derived()
print(obj.message())
AAttributeError
BDerived message
CNone
DBase message
Attempts:
2 left
💡 Hint
The Derived class replaces the Base method without calling it.
Predict Output
advanced
2:30remaining
Output with multiple inheritance and method overriding
What is the output of this code?
Python
class A:
    def speak(self):
        return "A speaks"

class B(A):
    def speak(self):
        return "B speaks"

class C(A):
    def speak(self):
        return "C speaks"

class D(B, C):
    pass

obj = D()
print(obj.speak())
AB speaks
BA speaks
CC speaks
DTypeError
Attempts:
2 left
💡 Hint
Check the method resolution order (MRO) for class D.
Predict Output
advanced
2:00remaining
Output when overriding a method and changing return type
What will this code print?
Python
class Parent:
    def get_value(self):
        return 10

class Child(Parent):
    def get_value(self):
        return "Ten"

obj = Child()
print(obj.get_value())
ATen
BTypeError
C10
DAttributeError
Attempts:
2 left
💡 Hint
The Child method returns a string instead of an integer.
Predict Output
expert
2:30remaining
Output with method overriding and attribute access
What is the output of this code?
Python
class Parent:
    def __init__(self):
        self.value = 5
    def get_value(self):
        return self.value

class Child(Parent):
    def __init__(self):
        self.value = 10
    def get_value(self):
        return super().get_value() + 5

obj = Child()
print(obj.get_value())
A10
B5
C15
DAttributeError
Attempts:
2 left
💡 Hint
Consider which __init__ method runs and what self.value is when super().get_value() is called.