Bird
0
0

Find the error in this code:

medium📝 Debug Q7 of 15
Python - Inheritance and Code Reuse
Find the error in this code:
class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    def __init__(self, name, age):
        self.age = age

c = Child("Anna", 10)
print(c.name, c.age)
AChild's __init__ does not call Parent's __init__
BParent class __init__ has wrong parameter
CChild class should not have __init__ method
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check constructor chaining

    Child's __init__ overrides Parent's but does not call Parent's __init__, so self.name is not set.
  2. Step 2: Identify missing call to Parent's __init__

    To fix, Child's __init__ should call super().__init__(name) to set name.
  3. Final Answer:

    Child's __init__ does not call Parent's __init__ -> Option A
  4. Quick Check:

    Call parent's __init__ in child's __init__ [OK]
Quick Trick: Call super().__init__() in child's constructor to inherit attributes [OK]
Common Mistakes:
  • Not calling parent's __init__ in child
  • Assuming parent's __init__ runs automatically
  • Ignoring missing attribute errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes