Object Oriented Programming Challenge - Solution
For this challenge, create a bank account class that has two attributes:
owner
balance
and two methods:
deposit
withdraw
As an added requirement, withdrawals may not exceed the available balance.
Instantiate your class, make several deposits and withdrawals, and test to make sure the account can't be overdrawn.
In [1]: 1 class Account:
2 def __init__(self,owner,balance=0):
3 self.owner = owner
4 self.balance = balance
5
6 def __str__(self):
7 return f'Account owner: {self.owner}\nAccount balance: ${self.balance}'
8
9 def deposit(self,dep_amt):
10 self.balance += dep_amt
11 print('Deposit Accepted')
12
13 def withdraw(self,wd_amt):
14 if self.balance >= wd_amt:
15 self.balance -= wd_amt
16 print('Withdrawal Accepted')
17 else:
18 print('Funds Unavailable!')
In [2]: 1 # 1. Instantiate the class
2 acct1 = Account('Jose',100)
In [3]: 1 # 2. Print the object
2 print(acct1)
Account owner: Jose
Account balance: $100
In [4]: 1 # 3. Show the account owner attribute
2 acct1.owner
Out[4]: 'Jose'
In [5]: 1 # 4. Show the account balance attribute
2 acct1.balance
Out[5]: 100
In [6]: 1 # 5. Make a series of deposits and withdrawals
2 acct1.deposit(50)
Deposit Accepted
In [7]: 1 acct1.withdraw(75)
Withdrawal Accepted
In [8]: 1 # 6. Make a withdrawal that exceeds the available balance
2 acct1.withdraw(500)
Funds Unavailable!
Good job!