Banking5.py

From OpenHatch wiki

class Bank:

   def __init__(self):
       self.usernamesPasswordsDictionary = {}
       self.users = []
       
   def add_user(self, username, password):
       user = User(username, password)
       self.usernamesPasswordsDictionary[user.username] = user.password
       self.users.append(user)
       print "Bank added user: " + user.username
       return user
   
   def login(self, username, password):
       if self.usernamesPasswordsDictionary[username] == password:
           return True
       print "Bank could not log you in."
       return False
       
   def transfer_money(self, amount, user_from, user_to):
       if (user_from.account.withdraw_money(amount)):
           user_to.account.add_money(amount)
           print "%s transferred $%d into %s's account." % (user_from.username, amount, user_to.username)
       
   def print_accounts(self):
       for u in self.users:
           print "%s has $%d in their account." % (u.username, u.account.balance)


class User:

   def __init__(self, theUsername, thePassword):
       self.username = theUsername
       self.password = thePassword
       self.account = Account(self)


class Account:

   def __init__(self, user):
       self.balance = 0
       
   def add_money(self, amount):
       self.balance = self.balance + amount
       print "Account just added %d bucks; new balance is: %d" % (amount, self.balance)
       
   def withdraw_money(self, amount):
       if self.balance > amount:
           self.balance = self.balance - amount
           print "Account just withdrew %d bucks; new balance is: %d" % (amount, self.balance)
           return True
       else:
           print "Withdrawal Aborted: you do not have enough money in your account."
           return False
           

class Transaction:

   def __init__(self, bank, user):
       self.bank = bank
       self.user = user
       
   def login(self, username, password):
       return self.bank.login(username, password)
       
   def deposit(self, amount):
       self.user.account.add_money(amount)
       
   def withdraw(self, amount):
       self.user.account.withdraw_money(amount)
       
   def transfer(self, amount, user_to):
       self.bank.transfer_money(amount, self.user, user_to)