[Tutor] class question

Tiger12506 keridee at jayco.net
Fri Jul 13 14:35:02 CEST 2007


> =======================================
> class BankAccount(object):
>    def __init__(self, initial_balance=0):
>        self.balance = initial_balance
>    def deposit(self, amount):
>        self.balance += amount
>    def withdraw(self, amount):
>        self.balance -= amount
>    def overdrawn(self):
>        return self.balance < 0
> my_account = BankAccount(15)
> my_account.withdraw(5)
> print my_account.balance
> =========================================
>
> This prints the expected "10".
>
> My question is, of what use can "overdrawn" be put? If I change the 
> withdrawal amount to 25, it prints the expected "-10", whether the class 
> contains the "overdrawn" function or not.
>
> Thanks,
>
> Dick Moores

A very good question. Now I have one for you. What does your bank do when 
you try to withdraw money? First, it checks to see if you have the money in 
your account. If you do, it subtracts that out of your balance. Whoever 
wrote that code failed to do the check within the withdraw function.

=======================================
class BankAccount(object):
   def __init__(self, initial_balance=0):
       self.balance = initial_balance
   def deposit(self, amount):
       self.balance += amount
   def withdraw(self, amount):
       if self.overdrawn():
          raise "Insufficient Funds Error"
       self.balance -= amount
   def overdrawn(self):
       return self.balance < 0
my_account = BankAccount(15)
my_account.withdraw(5)
print my_account.balance
=========================================

JS 



More information about the Tutor mailing list