python - TypeError : object does not support indexing -
i learned python. can't grab error in code. wrong?
class bankaccount: def __init__(self, initial_balance): """creates business relationship given balance.""" self = [initial_balance, 0] def deposit(self, amount): """deposits amount account.""" self += amount def withdraw(self, amount): """ withdraws amount account. each withdrawal resulting in negative balance deducts penalty fee of 5 dollars balance. """ self[0] -= amount if self[0] < 0: self[0] -= 5 self[1] += 1 def get_balance(self): """returns current balance in account.""" homecoming self[0] def get_fees(self): """returns total fees ever deducted account.""" homecoming 5*self[1] my_account = bankaccount(10) my_account.withdraw(15) my_account.deposit(20) my_account.get_balance(), my_account.get_fees()
the error is:
traceback (most recent phone call last): file "c:\python34\bank.py", line 28, in <module> my_account.withdraw(15) file "c:\python34\bank.py", line 15, in withdraw self[0] -= amount + 5 typeerror: 'bankaccount' object not back upwards indexing
self
value contains initial_balance
, count of how many withdrawals have happened.
it should this:
class bankaccount: overdraw_penalty = 5 def __init__(self, opening_balance=0): self.balance = opening_balance self.withdrawals = 0 def withdraw(self, amount): self.withdrawals += 1 self.balance -= amount if self.balance < 0: self.balance -= self.overdraw_penalty homecoming amount
note using self
access instance , class attributes, not trying assign straight it. also, have factored out "magic number" 5
, clearer happening.
also, implementation of get_fees
wrong - number of withdrawals incremented whether or not fee applied. should either store self.overdrawn_withdrawals
count separately or maintain running total self.fees
attribute.
finally, have added return amount
end of withdraw
- allows things like:
account2.deposit(account1.withdraw(100))
to transfer money between bankaccount
s.
python python-3.x
No comments:
Post a Comment