why does object turn to int after one use - python

I am learning python and while going through this OOP'S exercise:
For this challenge, create a bank account class that has two attributes:
owner
balance
and two methods:
deposit
withdraw
As an added requirement, withdrawals may not exceed the available balance.
Now the problem that I am facing is when I run the withdrawal once it works fine, but when I work it the second time it shows the error
" TypeError Traceback (most recent call last)
/var/folders/15/yqw5v0lx20q5lrbvg8bb69jr0000gn/T/ipykernel_79159/1232198771.py in
----> 1 acct1.withdraw(200)
TypeError: 'int' object is not callable"
here is my code
class Account:
def __init__(self, owner, balance = 0):
self.owner = owner
self.balance = balance
def __str__(self):
return f"the account holder is {self.owner} \nand the balance is {self.balance}"
def deposit(self,deposit):
self.deposit = deposit
self.balance += deposit
print("deposit accepted")
def withdraw(self, withdraw):
self.withdraw = withdraw
if self.balance >= withdraw:
self.balance -= withdraw
print("money withdrawn")
else:
print("Funds Unavailable!")
Kindly let me know where am I going wrong.

Do not name a method the same as a class attribute:
def withdraw(self, withdraw):
self.withdraw = withdraw
Possible solution:
def perform_withdraw(self, withdraw):
self.withdraw = withdraw

Before the first call to withdraw, the attribute withdraw of an instance of Account is the method that does your calculation.
After the first call to withdraw, the attribute is whatever argument you called withdraw with, because you issue self.withdraw = withdraw. Use another name or remove the line altogether if it is not needed.

Related

Python OOP, how to keep adding a number Instance attribute?

Trying to deposit into the wallet, it worked the first call, then when I call the deposit function again it would give me the error.
TypeError: 'int' object is not callable
Any solutions to this?
class Bank():
def __init__(self,wallet):
self.wallet = wallet
def withdraw(self,withdraw):
self.withdraw = withdraw
def deposit(self, deposit):
self.deposit = deposit
self.wallet += self.deposit
bank = Bank(0)
bank.deposit(500)
print(bank.wallet)
bank.deposit(500)
print(bank.wallet)
You're reassigning your deposit function to an integer in the line. self.deposit = deposit. Remove that :)

Issue with Classes - Program works as intended, but visual studio code is highlighting syntax error

My program is working as intended, it outputs the correct values when I perform a transfer from account 1 to account 2.
However, visual studio code is underlining "self" in red (e.g. telling me "Instance of 'Account' has no 'filepath' member)
Could you help me understand what I'm doing wrong? thanks so much!
Here is my code and output below, thanks so much!
class Account:
def __init__(self):
filepath=self.filepath #self is underlined here
with open(filepath,"r") as file:
self.balance = int(file.read())
def withdraw(self, amount):
self.balance -= amount
def deposit(self, amount):
self.balance += amount
def transfer(self, amount, receiver):
self.newbalance = self.balance - amount
receiver.newbalance = receiver.balance + amount
print(self.accountname,"balance is",self.balance) #self is underlined here
print(receiver.accountname,"balance is",receiver.balance)
print(self.accountname,"transfering",amount,"to",receiver.accountname) #self is underlined here
print(self.accountname, "new balance is",self.newbalance) #self is underlined here
print(receiver.accountname, "new balance is",receiver.newbalance)
class Louis(Account):
accountname = "Louis"
filepath = "louis.txt"
class Romain(Account):
accountname = "Romain"
filepath = "romain.txt"
romain = Romain()
louis = Louis()
romain.transfer(99,louis)
Output
Romain balance is 2000
Louis balance is 1000
Romain transfering 99 to Louis
Romain new balance is 1901
Louis new balance is 1099
I believe the inheritance is leading to some confusion here. While Louis and Roman both initialize filepath, the account base class never initializes filepath. Visual studio is flagging this a syntax error because if you had have initialized an instance of Account, your code would have raised an AttributeError. For instance:
class Account:
def __init__(self):
filepath=self.filepath #self is underlined here
with open(filepath,"r") as file:
self.balance = int(file.read())
def withdraw(self, amount):
self.balance -= amount
def deposit(self, amount):
self.balance += amount
def transfer(self, amount, receiver):
self.newbalance = self.balance - amount
receiver.newbalance = receiver.balance + amount
print(self.accountname,"balance is",self.balance) #self is underlined here
print(receiver.accountname,"balance is",receiver.balance)
print(self.accountname,"transfering",amount,"to",receiver.accountname) #self is underlined here
print(self.accountname, "new balance is",self.newbalance) #self is underlined here
print(receiver.accountname, "new balance is",receiver.newbalance)
class Louis(Account):
accountname = "Louis"
filepath = "louis.txt"
class Romain(Account):
accountname = "Romain"
filepath = "romain.txt"
romain = Romain()
louis = Louis()
romain.transfer(99,louis)
account = Account()
Output
Romain balance is 2000
Louis balance is 1000
Romain transfering 99 to Louis
Romain new balance is 1901
Louis new balance is 1099
Traceback (most recent call last):
File "/home/test.py", line 38, in <module>
account = Account()
File "/home/test.py", line 4, in __init__
filepath=self.filepath #self is underlined here
AttributeError: 'Account' object has no attribute 'filepath'
The problem is that you only set filepath in the subclasses. If you try to create an Account object rather than a Louis or Romain, or you use another subclass that doesn't set filepath, you'll get an error. VS Code doesn't have any way of knowing that you never do this, it just analyzes the class by itself.
your filepath is a Class variable not an Instance variable
Louis and Romain need to be instances of an Account
class Account:
def __init__(self, accountname, filepath):
self.filepath = filepath
self.accountname = accountname
self.balance = 0
with open(self.filepath,"r") as file:
self.balance = int(file.read())
def withdraw(self, amount):
self.balance -= amount
def deposit(self, amount):
self.balance += amount
def transfer(self, amount, receiver):
self.newbalance = self.balance - amount
receiver.newbalance = receiver.balance + amount
print(self.accountname,"balance is",self.balance)
print(receiver.accountname,"balance is",receiver.balance)
print(self.accountname,"transfering",amount,"to",receiver.accountname)
print(self.accountname, "new balance is",self.newbalance)
print(receiver.accountname, "new balance is",receiver.newbalance)
romain = Account("Romain", "romain.txt")
louis = Account("Louis", "louis.txt")
romain.transfer(99,louis)

How to implement transfer method for a account class in python

So, I'm making a Account class in python. It has the basic functions of deposit, withdrawing, and checking your balance. I'm having trouble with a transfer method though.
This is my code(sorry for the code dump):
class Account:
"""simple account balance of bank"""
def __init__ (self, name, balance):
self.name = name
self.balance = balance
print('Account of ' + self.name)
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.statement()
def withdrawal(self, amount):
if amount > 0 and self.balance > amount:
self.balance -= amount
self.statement()
else:
print("the ammount in your is not sufficent")
self.statement()
def statement(self):
print("Hi {} your current balance is {}".format(self.name,self.balance))
def transfer(self, amount, name):
self.balance = self.balance - amount
name.balance = name.balance + amount
return name.balance()
Now, it works for
abc = Account("abc", 0)
abc.deposit(1000)
siddharth = Account("siddharth", 159)
So how do I run following code:
siddharth.transfer(11, "abc")
siddharth.transfer(11, Account.abc)
also, how do I create account "abc" if account "abc" doesn't exist
Your code will be your best lesson about taking care of variables/parameters naming. Your method transfer(self, amount, name) should be transfer(self, amount, account). I think that now, it will be obvious that the correct code is
abc = Account("abc", 0)
abc.deposit(1000)
siddharth = Account("siddharth", 159)
siddharth.transfer(11, abc)
Be really careful on misleading names.
Aside of your question, I don't think that an Account should have a transfer method. An Account only cares about deposits and withdraws, not about what is done with them. IMO Transfer should be a function with 2 Account parameters, withdrawing from the first, making a deposit on the second. This is just to follow the Single Responsibility principle.
Following the same principle, don't put print functions in an Account. Consider that you don't know the context in which your class will be used. If it is in a web app, prints are redirected to /dev/null…
Finally, always do what you said you'll do. If I have an account with a balance b, I expect that after the call to deposit with a value v, my account balance will be b + v. No matter the value of v. You are right to check the value and not adding a negative value (that is a withdraw) so you have to warn the caller that you'll not add the value, so rise an exception. Same for withdraw.
You can first have an array of all accounts somewhere declared. Then, you can first try to find if an account exists. If not, create an account and pass them.
allAccounts = []
#create bunch of accounts including 'abc'
siddharth = Account("siddharth", 159)
searchResult = [x for x in allAccounts if x.name == 'abc']
#assuming that account names are unique
if len(searchResult) == 0:
acc = Account("abc", 11)
else:
acc = searchResult[0]
siddarth.transfer(11, acc)

Unable to call a method within a schedule job

I have a class that looks like this:
class Account(object):
"""A simple bank account"""
def __init__(self, balance=0.0):
"""
Return an account object with a starting balance of *balance*.
"""
self.balance = balance
def withdraw(self, amount):
"""
Return the balance remaining after withdrawing *amount* dollars.
"""
self.balance -= amount
return self.balance
def deposit(self, amount):
"""
Return the amount remaining after depositing *amount* dollars.
"""
self.balance += amount
return self.balance
I'll initialize it in xyz:
xyz = Account(balance=6000)
xyz.balance
> 6000
I also have a dumb printing function:
def thing():
print("I am doing a thing...")
When I try to call the deposit method in my schedule flow:
import schedule
# this works
# schedule.every(5).seconds.do(thing)
# this doesn't work
schedule.every(5).seconds.do(xyz.deposit(2300))
while True:
schedule.run_pending()
I get the following error:
TypeError: the first argument must be callable
Any ideas? Is it even possible to call methods within a schedule flow?
Not familiar with schedule, but it seems like do() wants a callable, i.e. a method. You're giving it the return value of xyz.deposit(2300), rather than the method xyz.deposit and the argument 2300. Try this:
schedule.every(5).seconds.do(xyz.deposit, 2300)

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

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.

Categories

Resources