Problem overview
You build a BankAccount class that guards its own balance. Outside code never changes the money directly. It asks the object through methods, and the methods check the rules first. Keeping data behind methods that enforce rules is called encapsulation.
The class has four members:
__init__(self, initial_balance)creates an account with a starting balance.deposit(self, amount)adds money. A zero or negative amount is ignored: no error, and the balance stays as it was.withdraw(self, amount)removes money and returnsTrue. It returnsFalseand changes nothing when the amount is zero, negative or larger than the balance. Withdrawing exactly the whole balance is allowed.get_balance(self)returns the balance.
The driver starts with 100, deposits 50, withdraws 30 and then tries to withdraw 200. It prints the balance, tries three invalid operations, prints again, empties the account and finally asks for one more unit.
Approach: a private attribute and guard clauses
Python has no private keyword. The convention is to start the attribute name with an underscore: self._balance tells other programmers that it is internal and that they should use the methods. Python doesn't enforce this. Code that writes account._balance = 1000000 succeeds and get_balance() then returns 1000000. The underscore is a promise between programmers, and the methods are the intended door.
Both deposit and withdraw use a guard clause: the first line rejects bad input and leaves the method, so the rest of the body only sees valid amounts. The two methods differ in how they say no. deposit just returns, which gives None. withdraw must tell the caller what happened, so it returns False on refusal and True on success, and the driver uses that answer in its if statements.
Step by step
- Declare the class
BankAccount. All the account's state and rules live inside it. - Start the constructor,
__init__(self, initial_balance). Python calls it once when you writeBankAccount(100), andselfis the new account. - Store the starting balance in
self._balance. Withself.the value outlives the constructor, so the other methods can use it. - Start
deposit(self, amount). It changes the balance and answers nothing. - Add the guard:
if amount <= 0: return, written on one line. A deposit of zero or less is ignored. - Add the amount to
self._balance. Only positive amounts get this far. - Start
withdraw(self, amount), which will answerTrueorFalse. - Refuse bad requests with one guard:
amount <= 0oramount > self._balancereturnsFalse. The comparison is>, not>=, so asking for exactly the balance passes. - Subtract the amount from the balance.
- Return
True: reaching this line means the money left the account. - Start
get_balance(self), a getter that lets outside code read the balance without a reason to touch it. - Return
self._balancefrom it.
The solution in Python
class BankAccount:
def __init__(self, initial_balance):
self._balance = initial_balance
def deposit(self, amount):
if amount <= 0: return
self._balance += amount
def withdraw(self, amount):
if amount <= 0 or amount > self._balance: return False
self._balance -= amount
return True
def get_balance(self):
return self._balance
account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
account.withdraw(200)
print("Balance: " + str(int(account.get_balance())))
account.deposit(-20)
account.deposit(0)
account.withdraw(-5)
print("Balance: " + str(int(account.get_balance())))
if account.withdraw(120):
print("Withdrew all")
print("Balance: " + str(int(account.get_balance())))
if not account.withdraw(1):
print("Rejected")
The class ends after get_balance. Everything below it is the driver that uses the class.
Python details worth a look
- One-line guards.
if amount <= 0: returnis legal when the body is a single statement. Indepositthe barereturnends the method and gives backNone. orshort-circuits. Inamount <= 0 or amount > self._balance, the second test only runs when the first is false. Both parts are plain comparisons, so the order doesn't change the result here.selfis explicit. Every method listsselffirst, and every attribute is read asself._balance. A bare_balancewould be a different name that doesn't exist.int(...)in the driver. The driver printsstr(int(account.get_balance())). With whole numbers theintchanges nothing. Your class doesn't convert: withdeposit(0.5)on an empty account,get_balance()returns0.5.
What the driver prints
Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected
100 plus 50 minus 30 is 120, and the refused withdrawal of 200 leaves it there. The deposits of -20 and 0 and the withdrawal of -5 are all ignored, so the balance is still 120. Withdrawing 120 succeeds and empties the account, and withdrawing 1 more is rejected.
Edge cases and common mistakes
- The whole balance.
BankAccount(100).withdraw(100)returnsTrueand leaves 0. Writingamount >= self._balancein the guard would wrongly refuse it. - Overdrawing. After that,
withdraw(1)returnsFalseand the balance stays 0. On an account with 50,withdraw(51)returnsFalseand the balance is still 50. - A zero amount.
withdraw(0)returnsFalse, even on an empty account, because the amount is not positive. - Forgetting the return value. Without
return Trueat the end, a successful withdrawal returnsNone. The driver'sif account.withdraw(120)would then be false andWithdrew allwould never print. - Changing the balance before checking. Subtracting first and validating afterwards leaves the account changed on a refusal. Put the guard first.
- Skipping
self.. Writing_balance = initial_balancein the constructor creates a local variable that disappears when the constructor ends.
Key takeaways
- A leading underscore marks an attribute as internal. It is a convention, and the methods are the intended way in.
- Guard clauses at the top of a method keep the invalid cases out of the main logic.
- A method that can refuse should say so through its return value.
