Hi there,
I'm trying to create a class with whats below.
I made it and it works but i need to be able to withdraw an amount from the balance.

I'm just having trouble with the layout and whether i got the right idea?

Is the underlined area on the right track?

class BankAccount:
    def __init__(self, balance, interestrate, accountnumber):
        self.balance = balance
        self.interestrate = interestrate
        self.accountnumber = accountnumber
    [B][U]def withdraw(self, amount):[/U][/B]
        [B][U]self.amount = self.balance-self.amount[/U][/B]

p1 = BankAccount(5500, 0.2, 001)

Because when i type: p1.withdraw(500) (i'm wanting to withdraw 500 from the balance of 5500.)

i get the error message:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in ?
    p1.withdraw(500)
  File "H:\Year 2\217CR James S\Lab 1\BankAccount.py", line 7, in withdraw
    self.amount = self.balance-self.amount
AttributeError: BankAccount instance has no attribute 'amount'

Thanks in advance

Recommended Answers

All 3 Replies

It should be

def withdraw(self, amount):
        self.balance -= amount

There is no self.amount , only the paramater amount .

Thanks!
Thats sorted it. Is there a rule that you dont enter any self.xxx code if it's not in the init or something. Just trying to understand here.

I obviously put in an if statment to stop them withdrawing more than allowed. Works great.

Thanks a bunch. :)

Is there a rule that you dont enter any self.xxx code if it's not in the init or something. Just trying to understand here.

There is no such rule. The BankAccount object stores a certain amount of data in it's members self.balance, self.interestrate and self.accountnumber. These values can be used in all the methods of the class.In your method "withdraw", the parameter "amount" is just a temporary value which is not stored in the BankAccount object.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.