Confused about why I'm getting a TypeError: 'int' object is not callable

StackOverflow https://stackoverflow.com/questions/23585262

  •  19-07-2023
  •  | 
  •  

سؤال

I've looked at similar questions and still have not been able to figure this out. I'm absolutely sure i'm making a very stupid mistake somewhere but I just can't seem to find it.

For this code.

class BankAccount:
    def __init__(self, initial_balance):
        self.balance = initial_balance

    def deposit(self, amount):
        self.deposit = amount
        self.balance = self.balance + self.deposit

    def withdraw(self, amount):
        self.withdraw = amount 
        self.balance = self.balance - self.withdraw
        self.fee = 5
        self.total_fees = 0

        if self.balance < 0:
            self.balance = self.balance - self.fee
            self.total_fees += self.fee 

    def get_balance(self):
        current_balance = self.balance
        return current_balance

    def get_fees(self):
        return self.total_fees

When I run the code everything works fine when I run this

my_account = BankAccount(10)
my_account.withdraw(15)
my_account.deposit(20)
print my_account.get_balance(), my_account.get_fees()

However, if I make an additional call to withdraw

my_account = BankAccount(10)
my_account.withdraw(15)
my_account.withdraw(15)
my_account.deposit(20)
print my_account.get_balance(), my_account.get_fees()

It throws this error.

TypeError: 'int' object is not callable

I don't understand why it works fine until I make an additional call to withdraw. Please help.

هل كانت مفيدة؟

المحلول

When you do self.deposit = amount, you overwrite your deposit method with the amount. You do the same in withdraw with self.withdraw = amount. You need to give the data attributes a different name from the methods (like call the method withdraw but the attribute withdrawalAmount or something like that).

نصائح أخرى

When you do this inside the withdraw method

self.withdraw = amount 

you replace the it with whatever amount is. Next time you call withdraw, you get the amount object. Which in your case is an int.

The same applies to deposit:

self.deposit = amount

Give your data members names that are different to your methods.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top