Bird
Raised Fist0

You want to implement a class Wallet with a private attribute __amount that can be read from outside but only modified via a method add_money(). Which code snippet correctly achieves this?

hard🚀 Application Q8 of Q15
Python - Encapsulation and Data Protection
You want to implement a class Wallet with a private attribute __amount that can be read from outside but only modified via a method add_money(). Which code snippet correctly achieves this?
Aclass Wallet: def __init__(self): self.amount = 0 def add_money(self, value): self.amount += value
Bclass Wallet: def __init__(self): self.__amount = 0 def add_money(self, value): self.__amount += value def get_amount(self): return self.__amount
Cclass Wallet: def __init__(self): self.__amount = 0 def add_money(self, value): self.amount += value def get_amount(self): return self.__amount
Dclass Wallet: def __init__(self): self.__amount = 0 def add_money(self, value): self.__amount = value def get_amount(self): return self.__amount
Step-by-Step Solution
Solution:
  1. Step 1: Private attribute initialization

    Initialize __amount as a private attribute with self.__amount = 0.
  2. Step 2: Controlled modification

    Method add_money adds to __amount safely.
  3. Step 3: Provide read access

    Method get_amount returns the private attribute value.
  4. Final Answer:

    class Wallet: def __init__(self): self.__amount = 0 def add_money(self, value): self.__amount += value def get_amount(self): return self.__amount correctly implements private attribute with controlled access.
  5. Quick Check:

    Private attribute modified only via method [OK]
Quick Trick: Use methods to modify private attributes [OK]
Common Mistakes:
MISTAKES
  • Using public attribute instead of private
  • Modifying attribute directly without method
  • Overwriting instead of adding in add_money

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes