logo CodeStepByStep logo

BankAccount_transfer

Language/Type: Python classes
Related Links:

Add a method named transfer to the BankAccount class that moves money between two accounts. Use your BankAccount class solution from the previous exercises as a starting point to solve this exercise.

Suppose that a class of objects named BankAccount has already been created that remembers information about a user's account at a bank. The class includes the following public members:

member name type description
BankAccount(name) constructor constructs a new account for the person with the given name, with $0.00 balance
ba._name,
ba._balance
data attributes private attributes storing account's name and balance
ba.name property the account name as a string (read-only)
ba.balance property the account balance as a real number (read-only)
ba.deposit(amount) method adds the given amount of money, as a real number, to the account balance; if the amount is negative, does nothing
ba.withdraw(amount) method subtracts the given amount of money, as a real number, from the account balance; if the amount is negative or exceeds the account's balance, does nothing

Add a mutator method named transfer to the class that moves money from the current bank account to another account. The method accepts two parameters aside from self: a second BankAccount to accept the money, and a real number for the amount of money to transfer. There is a $5.00 fee for transferring money, so this much must be deducted from the current account's balance before any transfer. The method should modify the two objects such that the current object has its balance decreased by the given amount plus the $5 fee, and the other account's balance is increased by the given amount. If the account object does not have enough money to make the full transfer, transfer whatever money is left after the $5 fee is deducted. If this account has under $5 or the amount is 0 or less, no transfer should occur and neither account's state should be modified. The following are some example calls to the method:

# client code using the BankAccount class
ben = BankAccount("Ben")
ben.deposit(80.00)
hal = BankAccount("Hal")
hal.deposit(20.00)
ben.transfer(hal, 20.00)   # ben $55, hal $40  (ben -$25, hal +$20)
ben.transfer(hal, 10.00)   # ben $40, hal $50  (ben -$15, hal +$10)
hal.transfer(ben, 60.00)   # ben $85, hal $ 0  (ben +$45, hal -$50)
Member function: Write a member function that will become part of an existing class. You do not need to write the complete class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.