I'm having some troubles with my code. This is a budget app in which you can add categories and for every category you can deposit/withdraw money. The problem is that I have to save all the transactions in the format {"amount": x, "description":y} and to do this I create an object of class Amount which is defined in the code, but when I try to append the new Amount object to the list every single element of this list changes to the last object. I understood that when I add an object, all the other elements in the list refer to the same object, and that's probably the problem, but I cannot solve this. Can you help me? Thank you very much
(This bug happens in the methods deposit and withdraw)
class Amount:
tot={"amount":0,"description":""}
def __init__(self,am,descr=""):
self.tot["amount"]=am
self.tot["description"]=descr
def getTot(self):
return self.tot
class Category:
title=""
deposit_list=list()
balance=0
def __init__(self,name):
self.title=name
def __str__(self):
final_string=""
length=int((30-len(self.title))/2)
for i in range(0,length):
final_string+="*"
final_string+=self.title
for i in range(0,length):
final_string+="*"
final_string+="\n"
for x in self.deposit_list:
y=x.getTot()["description"]
y=y[0:23]
z=float(x.getTot()["amount"])
final_string+=y
l=len(y)
if l<23:
for i in range(l,23):
final_string+=" "
z=str(z)
l=len(z)
if l<7:
for i in range(l,7):
final_string+=" "
final_string+=z
final_string+="\n"
final_string+="Total: "
final_string+=str(self.balance)
return final_string
def get_balance(self):
return self.balance
def getTitle(self):
return self.title
def deposit(self,amount,description=""):
if description!="":
description=str(description)
dep=Amount(amount,description)
self.deposit_list.append(dep)
self.balance+=dep.getTot()["amount"]
def withdraw(self,amount,description=""):
if description!="":
description=str(description)
wd=Amount(-1*amount,description)
if self.check_funds(amount):
self.deposit_list.append(wd)
self.balance+=wd.getTot()["amount"]
return True
else:
return False
def transfer(self,amount,dest):
descr_dest="Transfer from "
descr_dest+=self.getTitle()
descr_src="Transfer to "
descr_src+=dest.getTitle()
if self.withdraw(amount,descr_src)==True:
dest.deposit(amount,descr_dest)
return True
else:
return False
def check_funds(self,amount):
if amount>self.balance:
return False
else:
return True
def create_spend_chart(categories):
return
Edit:
I'm sorry, here is a test you can run
import budget
from unittest import main
food = budget.Category("Food")
food.deposit(1000, "initial deposit")
food.withdraw(10.15, "groceries")
food.withdraw(15.89, "restaurant and more food for dessert")
clothing = budget.Category("Clothing")
food.transfer(50, clothing)
print(food)
It should print this:
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
I also have to say that it should print only the first 23 characters of the description, but this shouldn't be important for the question.
#frno that was an attempt to avoid the problem described in the question, I edited the code as it was before that update
Thank you!
Related
I am having a hard time figuring out how to update selected references of a method from vscode. Right-clicking on the method name doesn't give the options to choose and update the references. New to Python and vscode and trying to figure out the nuances around it. Can some help me with this please!
Here are the classes - I have a class Player_Account
class Player_Account:
def __init__(self,owner,balance):
self.owner = owner
self.balance = balance
def deposit(self,balance):
self.balance += balance
return "Amount added to players pot !"
def withdraw(self,amount): # I need to update this method name to withdraw_amount
if self.balance<amount:
return "Funds Unavailable"
else:
self.balance -= amount
return "Money added to hand !"
def __str__(self):
return f"Account owner : {self.owner} has outstanding balance of {self.balance}"
Another class Player
class Player:
def __init__(self,name):
self.name=name
self.hand = []
self.player_account:Player_Account = Player_Account(name,0)
def initial_money(self,amount):
self.player_account.balance = amount
def player_won_the_hand(self,amount):
self.player_account.deposit(amount)
return True
def player_betting_amount_for_the_round(self,amount):
value = self.player_account.withdraw(amount) # I need this reference to be automatically updated as well
if value == 'Funds Unavailable':
return False
else:
return True
I just tried.
set cursor on def withdraw
press F2 (rename symbol)
change name to withdraw_amount and press Enter
it takes a few seconds but both are changed
I use PyLance.
I'm new to programming with python and I'm working on the python 4 everybody course. For that I need to build a budget app. In specific, this is the first two tasks:
Complete the Category class in budget.py. It should be able to instantiate objects based on different budget categories like food, clothing, and entertainment. When objects are created, they are passed in the name of the category. The class should have an instance variable called ledger that is a list. The class should also contain the following methods:
A deposit method that accepts an amount and description. If no description is given, it should default to an empty string. The method should append an object to the ledger list in the form of {"amount": amount, "description": description}.
A withdraw method that is similar to the deposit method, but the amount passed in should be stored in the ledger as a negative number. If there are not enough funds, nothing should be added to the ledger. This method should return True if the withdrawal took place, and False otherwise.
My attempt for now is the following:
class Category:
def __init__(self):
self.ledger = []
Total = 0
def deposit(self, amount, *description):
self.ledger.append({"amount": amount, "description": description})
return self.ledger
def withdraw(self, withdrawal):
for x in self.ledger:
if x == int():
return sum
self.ledger.append({"withdrawal": withdrawal})
return self.ledger
I think I have multiple questions:
What is a list with {} as one Item? Is it a 5.4. "Set"?
How can I now implement the requirement of the withdraw method "If there are not enough funds, nothing should be added to the ledger." I think I need to sum up all the integers of the list self.ledger, but idk how to grab those from it and sum it up. I tried as you can see a for loop, but I think that is incorrect syntax?
I really appreciate every help and am grateful for also some background knowledge!
Thanks in advance!
Lukas
{} is en empty dict. An empty set is set()
This should do for the withdraw function :
def withdraw(self, amount, description):
balance = sum(transaction["amount"] for transaction in self.ledger)
if balance >= withdrawal :
self.ledger.append({"amount": -amount, "description": description})
return True
else :
return False
return self.ledger
This use a generator as an argument for the builtin sum function. This may be a bit advanced if you are just starting python so you can also compute the balance with more beginner friendly code :
balance = 0
for transaction in ledger:
balance = balance + transaction["amount"]
# you can shorten the line above to
# balance += transaction["amount"]
This is roughly equivalent to what the sum and the generator syntax do.
Out of curiosity, is the * in front of description argument in your deposit function a typo ?
So, some things for clarification.
self.ledger = []: The [] makes the ledger a list, and the self. part makes it an instance variable, only applicable to a specific instance of the class Category
As stated in the comments, {"key": "value"} is a dict object. Using self.ledger.append({"key": "value"}) adds the dict object {"key": "value"} to the ledger list.
Normally if you want to keep track of a number inside a class, you create an instance variable and update it when it gets changed. See the usage of self.total below.
Recalculating the total can also be done, see the method update_total() below.
I added some testing below.
class Category:
def __init__(self):
self.ledger = []
# total also needs the "self." to make it an instance variable, just
# as the ledger above
# if you omit the "self."" it's a localized variable only available
# to the __init__ method itself.
self.total = 0
def deposit(self, amount, *description):
self.ledger.append({"amount": amount, "description": description})
# add the amount to the total
self.total += amount
return self.ledger
def withdraw(self, withdrawal):
# make the withdrawal negative
if abs(withdrawal) == withdrawal:
withdrawal = 0 - withdrawal
# check if there's enough in the total
if abs(withdrawal) <= self.total:
# update the total
self.total += withdrawal
# add to the ledger
self.ledger.append({"withdrawal": withdrawal})
else:
# you could return an error message here
pass
return self.ledger
def update_total(self):
total = 0
for item in self.ledger:
# need to check if the amount key is in the dict object
if "amount" in item:
total += item["amount"]
# this check below is not needed but it ensures future compatability
elif "withdrawal" in item:
total += item["withdrawal"]
# just because, you can check if the totals match
if self.total != total:
print(
f"""Difference in totals found. Someone is cheating :-|
Instance total: {self.total}
Calculated total: {total}"""
)
# set the instance variable to the local variable
self.total = total
return self.total
from pprint import pprint
nr1 = Category()
nr2 = Category()
for i in range(10):
nr1.deposit(i, f"deposit - {i}")
pprint(nr1.ledger)
print(f"Total: {nr1.total}")
nr1.withdraw(10)
print(f"Total: {nr1.total}")
nr1.withdraw(-10)
print(f"Total: {nr1.total}")
nr1.withdraw(99999)
print(f"Total: {nr1.total}")
pprint(nr1.ledger)
print(nr1.update_total())
nr1.total = 123
print(nr1.update_total())
# just to show that the above only updated the values inside the nr1 instance.
print(f"Total for nr2: {nr2.total}")
need help about my code (python):
class Account:
def __init__(self, money):
self.money= money
def __str__(self):
return f'Money in the bank: {self.money} dollar'
def withdraw(self,withdraw):
self.withdraw = withdraw
money = self.money-self.withdraw
return money
print(Account.withdraw(20000,1000))
What I want from code above is the code will print my remaining money (19000), but I always got error
'int' object has no attribute 'withdraw'.
I have tried a lot of things for 4 hours but got no satifying result.
This is my first question in this forum, i am sorry if the formatting is not right.
Thank you in advance :)
Below I have made some small changes in your code and it is working as you expect.
Defined new variable withdrawMoney to track the withdraw amount.
Some changes in string format.
Returned the updated amount every time.
class Account:
def __init__(self, money):
self.money= money
self.withdrawMoney = 0
def __str__(self):
return "Money in the bank: {} dollar".format(self.money)
def withdraw(self,withdrawMoney):
self.withdrawMoney = withdrawMoney
self.money = self.money-self.withdrawMoney
return self.money
acc = Account(20000)
print(acc.withdraw(1000)) # 19000
print(acc.withdraw(1000)) # 18000
I'm learning Python and currently learning Classes.
I'm not able to print the instance of a class, the code is as follows.
class CreditCard:
""" This is properly intended, but CNTRL+K resulted in unindentation
(stackoverflow's cntrl+k)"""
def __init__(self,customer,bank,account,limit):
""" Initializing the variables inside the class
Setting the Initial Balance as Zero
Customer : Name of the Customer
bank : Name of the Bank
balance : will be zero, initial
account : accoount number or identifier, generally a string
limit : account limit/ credit limit
"""
self.customer = customer
self.bank = bank
self.accnt=account
self.limit = limit
self.balance = 0
def get_customer(self):
""" returns the name of the customer """
return self.customer
def get_bank(self):
""" returns the Bank name """
return self.bank
def get_account(self):
""" returns the Account Number """
return self.account
def get_limit(self):
""" returns the Credit Limit """
return self.limit
def get_balance(self):
""" returns the Balance """
return self.balance
def charge(self,price):
""" swipe charges on card, if sufficient credit limit
returns True if transaction is processed, False if
declined """
if price + self.balance > self.limit:
return False
else:
self.balance=price+self.balance
# abve can be written as
# self.balance+=price
return True
def make_payment(self,amount):
""" cust pays money to bank, that reduces balance """
self.balance = amount-self.balance
# self.balance-=amount
def __str__(self):
""" string representation of Values """
return self.customer,self.bank,self.account,self.limit
I'd run that with no error.
I've created an instance,
cc=CreditCard('Hakamoora','Duesche',12345678910,5000)
this is what I've been getting.
>>> cc
<__main__.CreditCard instance at 0x0000000002E427C8>
what should I include to make it print the instance, like
>>cc=CreditCard('Hakamoora','Duesche',12345678910,5000)
>>cc
>>('Hakamoora','Duesche',12345678910,5000)
Kindly use less technical terms(Newbie here)
pastebinlink : https://paste.ee/p/rD91N
also tried these,
def __str__(self):
""" string representation of Values """
return "%s,%s,%d,%d"%(self.customer,self.bank,self.account,self.limit)
and
def __str__(self):
""" string representation of Values """
return "({0},{1},{2},{3})".format(self.customer,self.bank,self.account,self.limit)
Thanks,
6er
You're mixing up __str__ and __repr__. Consider the following class:
class Test(object):
def __str__(self):
return '__str__'
def __repr__(self):
return '__repr__'
You can see which method is called where:
>>> t = Test()
>>> t
__repr__
>>> print(t)
__str__
>>> [1, 2, t]
[1, 2, __repr__]
>>> str(t)
'__str__'
>>> repr(t)
'__repr__'
Also, make sure both of those methods return strings. You're currently returning a tuple, which will cause an error like this to come up:
TypeError: __str__ returned non-string (type tuple)
Three points:
(1) Ensure that the indentation level of your definition of __str__ is such that it's a method of the CreditCard class. Currently it seems to be a function defined locally inside charge() and hence maybe not accessible as an instance method (But it's hard to tell for sure: charge() itself and its fellow methods are also incorrectly indented.)
(2) In __str__, return a string, rather than a tuple:
def __str__(self):
""" string representation of Values """
return str( ( self.customer,self.bank,self.account,self.limit ) )
(3) Define an additional __repr__ method: this will be used when displaying the object with
>>> cc
whereas __str__ will only be used when somebody (like print) tries to coerce the object to a str. Here's a minimal example:
def __repr__( self ): return str( self )
You forgot to turn the object into a string (or print it).
Try instead:
print(cc)
or
str(cc)
Is the file really indented properly? The last two methods (make_payment and __str__) are indented as if they are a part of the 'charge'-method.
I tested this on my system and the indentation on these two methods (especially __str__) caused the same error as yours. Removing the indentation allowed me to print the 'cc' variable the way you want it.
The is the corrected code,
I've learned a grea concept today, learnt about repr and str.
Example for class
Credit card
class CreditCard:
""" Just a Normal Credit Card """
def __init__(self,customer,bank,account,limit):
""" Initializing the variables inside the class
Setting the Initial Balance as Zero
Customer : Name of the Customer
bank : Name of the Bank
balance : will be zero, initial
account : accoount number or identifier, generally a string
limit : account limit/ credit limit
"""
self.customer = customer
self.bank = bank
self.account=account
self.limit = limit
self.balance = 0
def get_customer(self):
""" returns the name of the customer """
return self.customer
def get_bank(self):
""" returns the Bank name """
return self.bank
def get_account(self):
""" returns the Account Number """
return self.account
def get_limit(self):
""" returns the Credit Limit """
return self.limit
def get_balance(self):
""" returns the Balance """
return self.balance
def charge(self,price):
""" swipe charges on card, if sufficient credit limit
returns True if transaction is processed, False if
declined """
if price + self.balance > self.limit:
return False
else:
self.balance=price+self.balance
# abve can be written as
# self.balance+=price
return True
def make_payment(self,amount):
""" cust pays money to bank, that reduces balance """
self.balance = amount-self.balance
# self.balance-=amount
def __str__(self):
""" string representation of Values """
return str((self.customer,self.bank,self.account,self.limit))
Thank you so much
This question already exists:
Closed 11 years ago.
Possible Duplicate:
Fundamentals of Python Chapter 8 project 3
Hi I am a newbie programmer who just started to learn about python.
I have recently posted this same question before and I have solved it but my answer is not exactly what the question is asking.
I need help on why I need to implement a new method even though I could do the other way.
thanks
Question:
The __str__ method of the Bank class returns a string containing the
accounts in random order. Design and implement a change that causes
the accounts to be placed in the string by order of name.
[this is the part where I don't understand]
(Hint: You will also have to define a new method in the SavingsAccount class.)
class Bank(object):
def __init__(self):
self._accounts = {}
def __str__(self):
"""Return the string rep of the entire bank."""
pTemp =[]
for i in xrange(len(SavingsAccount.temp)-1):
if self._accounts.get(SavingsAccount.temp[i]).getName() >= self._accounts.get(SavingsAccount.temp[i+1]).getName():
temp = SavingsAccount.temp[i]
SavingsAccount.temp[i] = SavingsAccount.temp[i+1]
SavingsAccount.temp[i+1] = temp
for i in SavingsAccount.temp:
pTemp.append(self._accounts[i])
return '\n'.join(map(str, pTemp))
def add(self, account):
"""Inserts an account using its PIN as a key."""
self._accounts[account.getPin()] = account
def remove(self, pin):
return self._accounts.pop(pin, None)
def get(self, pin):
return self._accounts.get(pin, None)
def computeInterest(self):
"""Computes interest for each account and
returns the total."""
total = 0.0
for account in self._accounts.values():
total += account.computeInterest()
return total
class SavingsAccount(object):
"""This class represents a Savings account
with the owner's name, PIN, and balance."""
RATE = 0.02
temp = []
def __init__(self, name, pin, balance = 0.0):
self._name = name
self._pin = pin
self._balance = balance
SavingsAccount.temp.append(self)
def __str__(self):
result = 'Name: ' + self._name + '\n'
result += 'PIN: ' + self._pin + '\n'
result += 'Balance: ' + str(self._balance)
return result
def getBalance(self):
return self._balance
def getName(self):
return self._name
def getPin(self):
return self._pin
def deposit(self, amount):
"""Deposits the given amount and returns the
new balance."""
self._balance += amount
return self._balance
def withdraw(self, amount):
"""Withdraws the given amount.
Returns None if successful, or an
error message if unsuccessful."""
if amount < 0:
return 'Amount must be >= 0'
elif self._balance < amount:
return 'Insufficient funds'
else:
self._balance -= amount
return None
def computeInterest(self):
"""Computes, deposits, and returns the interest."""
interest = self._balance * SavingsAccount.RATE
self.deposit(interest)
def main():
bank = Bank()
bank.add(SavingsAccount("Zelda","1003",5000.00))
bank.add(SavingsAccount("Wilma","1001",4000.00))
bank.add(SavingsAccount("Fred","1002",1000.00))
print bank
main()
I think the question expects you to define ordering in the SavingsAccount class, that is, be able to determine whether an instance of SavingAccounts comes after or before another instance of SavingAccount. I don't want to write any spoiler here, but tell me if my hint is not enough ;).
UPDATE
Also, a common source of errors in Python with string ordering : a comes before z which comes before A which comes before Z ...
UPDATE2
more hints ;)
What you really want here is to sort a list of instances of SavingAccount according to a given criteria. There are 2 way to do this kind of thing. You can either :
have the one doing the sorting take care of it
or you can have the instances stored in your list taking care of it.
The second option is usually better because "the class to be sorted" should know better than anybody else how to sort itself (it's about encapsulation : not letting people outside control how your class works). Even though the question is not really clear, and the example is not very good (in my opinion), this is the option they would like you to chose.
The idea is that the Bank should just do something like this :
class Bank(object):
def __str__(self):
"""Return the string rep of the entire bank."""
#get a sorted copy of the list
#using default SavingAccount comparison
pTemp =sorted(self._accounts)
return '\n'.join(map(str, pTemp))
And SavingAccount contains information about how to sort.
You may want to have a look at this article from the PythonInfo Wiki.
Also: http://docs.python.org/reference/datamodel.html#object.__lt__