Reputation: 99
For some reason it seems like the code doesn't deduct from the right object and only adds to the receiver in my code, how can I fix this so the receiver gets the right amount added to his balance
class BankAccount:
def __init__(self, balance):
self.balance = balance
self.tamout = 0
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
def transfer(self, name, c):
self.balance -= c
name += c
return name
David = BankAccount(400)
John = BankAccount(200)
print "David balance is", David.balance
print "john balance is", John.balance
John.transfer(David.balance, 20)
print John.balance
print David.balance
The result is
David balance is 400
john balance is 200
180
400
Shouldn't the last print be 420?
Upvotes: 0
Views: 68
Reputation: 307
This should fix your issue
class BankAccount:
def __init__(self, balance):
self.balance = balance
self.tamout = 0
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
def transfer(self, receiver, c):
self.balance -= c
receiver.deposit(c)
return receiver
if __name__ == '__main__':
David = BankAccount(400)
John = BankAccount(200)
print "David balance is", David.balance
print "john balance is", John.balance
John.transfer(David, 20)
print John.balance
print David.balance
By using David instance and use the deposit
method on it
Upvotes: 2
Reputation: 4585
Your current transfer function receives a copy of the receiver's balance, not the original property.
Try this instead:
def transfer(self, name, c):
self.balance -= c
name.balance += c
return name
John.transfer(David, 20)
Upvotes: 1