Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Python - Encapsulation and Data Protection
What will be the output of this code?
class Person:
    def __init__(self, name):
        self.__name = name
    def get_name(self):
        return self.__name

p = Person('Anna')
print(p.get_name())
print(p.__name)
AAnna\nAnna
BAttributeError\nAnna
CAnna\nAttributeError
DAttributeError\nAttributeError
Step-by-Step Solution
Solution:
  1. Step 1: Understand private attribute access

    The attribute __name is private and cannot be accessed directly outside the class.
  2. Step 2: Check print statements

    Calling p.get_name() returns 'Anna' correctly. But p.__name causes AttributeError because it's private.
  3. Final Answer:

    Anna\nAttributeError -> Option C
  4. Quick Check:

    Private attribute direct access = AttributeError [OK]
Quick Trick: Private attributes cause error if accessed directly outside class [OK]
Common Mistakes:
  • Expecting direct access to private attribute
  • Ignoring AttributeError on private access
  • Confusing method call with attribute access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes