Bird
0
0

What will be the result of executing this code?

medium📝 Predict Output Q5 of 15
Python - Encapsulation and Data Protection
What will be the result of executing this code?
class Animal:
    def __init__(self):
        self.__species = 'Cat'

pet = Animal()
print(pet.__species)
ASyntaxError
BCat
CNone
DAttributeError: 'Animal' object has no attribute '__species'
Step-by-Step Solution
Solution:
  1. Step 1: Understand private attribute access

    Attributes with double underscores are name-mangled and cannot be accessed directly outside the class.
  2. Step 2: Analyze the code

    Trying to print pet.__species will raise an AttributeError because __species is private.
  3. Final Answer:

    AttributeError: 'Animal' object has no attribute '__species' -> Option D
  4. Quick Check:

    Direct access to double underscore attributes causes AttributeError [OK]
Quick Trick: Private attributes cause AttributeError if accessed directly [OK]
Common Mistakes:
  • Expecting direct access to private variables to work
  • Confusing private with protected attributes
  • Assuming private variables are accessible like public ones

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes