Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.23 KB | None | 0 0
  1. """
  2. File: bank.py
  3. This module defines the Bank class.
  4. """
  5. import pickle
  6. import random
  7. from savingsaccount import SavingsAccount
  8.  
  9. class Bank:
  10. """This class represents a bank as a collection of savings accounts.
  11. An optional file name is also associated
  12. with the bank, to allow transfer of accounts to and
  13. from permanent file storage."""
  14.  
  15. """The state of the bank is a dictionary of accounts and
  16. a file name. If the file name is None, a file name
  17. for the bank has not yet been established."""
  18.  
  19. def __init__(self, fileName = None):
  20. """Creates a new dictionary to hold the accounts.
  21. If a file name is provided, loads the accounts from
  22. a file of pickled accounts."""
  23. self.accounts = {}
  24. self.fileName = fileName
  25. if fileName != None:
  26. fileObj = open(fileName, 'rb')
  27. while True:
  28. try:
  29. account = pickle.load(fileObj)
  30. self.add(account)
  31. except Exception:
  32. fileObj.close()
  33. break
  34.  
  35. def __str__(self):
  36. """Returns the string representation of the bank."""
  37. return "\n".join([str(v) for (k, v) in sorted(self.accounts.items(), key=lambda cv: cv[1].getName())])
  38.  
  39.  
  40. def makeKey(self, name, pin):
  41. """Returns a key for the account."""
  42. return name + "/" + pin
  43.  
  44. def add(self, account):
  45. """Adds the account to the bank."""
  46. key = self.makeKey(account.getName(), account.getPin())
  47. self.accounts[key] = account
  48.  
  49. def remove(self, name, pin):
  50. """Removes the account from the bank and
  51. and returns it, or None if the account does
  52. not exist."""
  53. key = self.makeKey(name, pin)
  54. return self.accounts.pop(key, None)
  55.  
  56. def get(self, name, pin):
  57. """Returns the account from the bank,
  58. or returns None if the account does
  59. not exist."""
  60. key = self.makeKey(name, pin)
  61. return self.accounts.get(key, None)
  62.  
  63. def computeInterest(self):
  64. """Computes and returns the interest on
  65. all accounts."""
  66. total = 0
  67. for account in self._accounts.values():
  68. total += account.computeInterest()
  69. return total
  70.  
  71. def getKeys(self):
  72. """Returns a sorted list of keys."""
  73. # Exercise
  74. return []
  75.  
  76. def save(self, fileName = None):
  77. """Saves pickled accounts to a file. The parameter
  78. allows the user to change file names."""
  79. if fileName != None:
  80. self.fileName = fileName
  81. elif self.fileName == None:
  82. return
  83. fileObj = open(self.fileName, 'wb')
  84. for account in self.accounts.values():
  85. pickle.dump(account, fileObj)
  86. fileObj.close()
  87.  
  88. # Functions for testing
  89.  
  90. def createBank(numAccounts = 1):
  91. """Returns a new bank with the given number of
  92. accounts."""
  93. names = ("Brandon", "Molly", "Elena", "Mark", "Tricia",
  94. "Ken", "Jill", "Jack")
  95. bank = Bank()
  96. upperPin = numAccounts + 1000
  97. for pinNumber in range(1000, upperPin):
  98. name = random.choice(names)
  99. balance = float(random.randint(100, 1000))
  100. bank.add(SavingsAccount(name, str(pinNumber), balance))
  101. return bank
  102.  
  103. def testAccount():
  104. """Test function for savings account."""
  105. account = SavingsAccount("Ken", "1000", 500.00)
  106. print(account)
  107. print(account.deposit(100))
  108. print("Expect 600:", account.getBalance())
  109. print(account.deposit(-50))
  110. print("Expect 600:", account.getBalance())
  111. print(account.withdraw(100))
  112. print("Expect 500:", account.getBalance())
  113. print(account.withdraw(-50))
  114. print("Expect 500:", account.getBalance())
  115. print(account.withdraw(100000))
  116. print("Expect 500:", account.getBalance())
  117.  
  118. def main(number = 10, fileName = None):
  119. """Creates and prints a bank, either from
  120. the optional file name argument or from the optional
  121. number."""
  122. testAccount()
  123. print("\n----------Account details------------\n")
  124. if fileName:
  125. bank = Bank(fileName)
  126. else:
  127. bank = createBank(number)
  128. print(bank)
  129.  
  130. if __name__ == "__main__":
  131. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement