207k views
18 votes
The __str__ method of the Bank class (in bank. Py) returns a string containing the accounts in random order. Design and implement a change that causes the accounts to be placed in the string in ascending order of name. Implement the __str__ method of the bank class so that it sorts the account values before printing them to the console. In order to sort the account values you will need to define the __eq__ and __lt__ methods in the SavingsAccount class (in savingsaccount. Py). The __eq__ method should return True if the account names are equal during a comparison, False otherwise. The __it__ method should return True if the name of one account is less than the name of another, False otherwise

User Sir Hally
by
4.9k points

2 Answers

2 votes

class Bank(object):

def __str__(self):

"""Return the string rep of the entire bank."""

#get a sorted copy of the list

#using default SavingAccount comparison

pTemp =sorted(self._accounts)

return '\\'.join(map(str, pTemp))

User Jones J Alapat
by
4.1k points
7 votes

Based on the above, to sort the accounts in ascending order of name before displaying them, you'll need to modify the __str__ method of the Bank class and the __eq__ and __lt__ methods of the SavingsAccount class.

So, the SavingsAccount Class is:

Python

class SavingsAccount:

def __init__(self, name, balance):

self.name = name

self.balance = balance

def __str__(self):

return f"{self.name}: ${self.balance}"

def __eq__(self, other):

return self.name == other.name

def __lt__(self, other):

return self.name < other.name

While the Bank Class will be:

Python

class Bank:

def __init__(self):

self.accounts = []

def add_account(self, account):

self.accounts.append(account)

def __str__(self):

sorted_accounts = sorted(self.accounts)

return "\\".join(str(account) for account in sorted_accounts)

Based on the above modifications, the __str__ method of the Bank class will now sort the accounts before printing them to the console, displaying them in ascending order of name.

User Nebulous
by
5.4k points