Bird
0
0

Identify the error in this code related to encapsulation:

medium📝 Debug Q6 of 15
Python - Encapsulation and Data Protection
Identify the error in this code related to encapsulation:
class BankAccount:
    def __init__(self):
        self.__balance = 100
    def deposit(self, amount):
        self.__balance += amount

acc = BankAccount()
acc.__balance += 50
print(acc.__balance)
ANo error, prints 150
BSyntaxError due to private variable
CAttributeError on acc.__balance access
DTypeError when adding integer
Step-by-Step Solution
Solution:
  1. Step 1: Understand private variable access

    __balance is private and cannot be accessed directly outside the class.
  2. Step 2: Analyze acc.__balance += 50

    This line tries to access private variable directly, causing AttributeError.
  3. Final Answer:

    AttributeError on acc.__balance access -> Option C
  4. Quick Check:

    Direct private variable access = AttributeError [OK]
Quick Trick: Modify private variables only via class methods [OK]
Common Mistakes:
  • Trying to change private variables directly
  • Expecting no error on direct access
  • Confusing syntax error with attribute error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes