Bird
0
0

What will be printed when the following code is executed?

medium📝 Predict Output Q4 of 15
Python - Encapsulation and Data Protection
What will be printed when the following code is executed?
class DataHolder:
    def __init__(self):
        self._secret = 42

obj = DataHolder()
print(obj._secret)
A42
BAttributeError
CNone
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute access

    In Python, attributes with a single underscore prefix are accessible outside the class.
  2. Step 2: Analyze the code

    The attribute _secret is set to 42 in the constructor.
  3. Step 3: Print statement

    Printing obj._secret will output 42 without error.
  4. Final Answer:

    42 -> Option A
  5. Quick Check:

    Single underscore attributes are accessible [OK]
Quick Trick: Single underscore attributes are accessible outside class [OK]
Common Mistakes:
  • Expecting AttributeError due to underscore
  • Confusing with double underscore name mangling
  • Assuming attribute is private

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes