0
0
Pythonprogramming~20 mins

Parent and child classes in Python - Practice Problems & Coding Challenges

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

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

child = Child()
print(child.greet())
AHello from Parent
BHello from Child
CNone
DAttributeError
Attempts:
2 left
💡 Hint
Child class method with the same name replaces the parent's method.
Predict Output
intermediate
2:00remaining
Accessing parent method from child
What is the output of this code?
Python
class Parent:
    def greet(self):
        return "Hello from Parent"

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

child = Child()
print(child.greet())
AHello from Parent and Child
BHello from Parent
CHello from Child
DTypeError
Attempts:
2 left
💡 Hint
super() calls the parent class method.
Predict Output
advanced
2:00remaining
Instance variable shadowing in child class
What is the output of this code?
Python
class Parent:
    def __init__(self):
        self.value = 10

class Child(Parent):
    def __init__(self):
        self.value = 20

obj = Child()
print(obj.value)
AAttributeError
B10
C20
DNone
Attempts:
2 left
💡 Hint
Child's __init__ replaces Parent's __init__ unless explicitly called.
Predict Output
advanced
2:00remaining
Calling parent constructor in child class
What is the output of this code?
Python
class Parent:
    def __init__(self):
        self.value = 10

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.value = 20

obj = Child()
print(obj.value)
A20
B10
CAttributeError
DTypeError
Attempts:
2 left
💡 Hint
super().__init__() runs the parent's constructor first.
Predict Output
expert
2:00remaining
Multiple inheritance method resolution order (MRO)
What is the output of this code?
Python
class A:
    def greet(self):
        return "Hello from A"

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

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

class D(B, C):
    pass

d = D()
print(d.greet())
AHello from A
BTypeError
CHello from C
DHello from B
Attempts:
2 left
💡 Hint
Python uses the method resolution order (MRO) to decide which method to call.