Bird
Raised Fist0

Given this code, what is the output?

hard🚀 Application Q9 of Q15
Python - Encapsulation and Data Protection
Given this code, what is the output?
class Parent:
    def __init__(self):
        self._value = 5

class Child(Parent):
    def __init__(self):
        super().__init__()
        self._value = 10

p = Parent()
c = Child()
print(p._value, c._value)
A5 5
B10 10
C5 10
DAttributeError
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute assignment in parent and child

    Parent sets _value to 5; Child calls parent's init then sets _value to 10.
  2. Step 2: Check instances' attribute values

    Parent instance p has _value 5; Child instance c has _value 10.
  3. Final Answer:

    5 10 -> Option C
  4. Quick Check:

    Each instance has its own protected attribute value [OK]
Quick Trick: Child can override protected attribute after calling super().__init__() [OK]
Common Mistakes:
MISTAKES
  • Assuming parent's attribute changes child's value
  • Expecting both values to be same
  • Confusing instance attributes with class attributes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes