Bird
Raised Fist0

You want to store a private attribute __balance in a BankAccount class and allow safe updating only through a method that adds money. Which code snippet correctly implements this?

hard🚀 Application Q15 of Q15
Python - Encapsulation and Data Protection
You want to store a private attribute __balance in a BankAccount class and allow safe updating only through a method that adds money. Which code snippet correctly implements this?
Aclass BankAccount: def __init__(self): self.__balance = 0 def add_money(self, amount): self.__balance += amount def get_balance(self): return self.__balance
Bclass BankAccount: def __init__(self): self._balance = 0 def add_money(self, amount): self._balance += amount def get_balance(self): return self._balance
Cclass BankAccount: def __init__(self): self.balance = 0 def add_money(self, amount): self.balance += amount def get_balance(self): return self.balance
Dclass BankAccount: def __init__(self): self.__balance = 0 def add_money(self, amount): self.balance += amount def get_balance(self): return self.__balance
Step-by-Step Solution
Solution:
  1. Step 1: Check private attribute usage

    class BankAccount: def __init__(self): self.__balance = 0 def add_money(self, amount): self.__balance += amount def get_balance(self): return self.__balance uses self.__balance consistently and privately.
  2. Step 2: Verify method updates and access

    The add_money method safely updates __balance, and get_balance returns it correctly.
  3. Final Answer:

    The code using self.__balance consistently in all methods -> Option A
  4. Quick Check:

    Private attribute updated only inside class methods [OK]
Quick Trick: Update private attributes only via class methods [OK]
Common Mistakes:
MISTAKES
  • Updating private attribute outside class
  • Mixing private and public attribute names
  • Not providing method to access private data

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes