Category-project. (how to create an instance list variable in the class))

Tell us what’s happening:
I trying to create the “ledger” list for every instance but I don’t know what is wrong with my code
with running the code :
food = Category(‘food’)
food.deposit(1000,“food initial deposit”)
food.withdraw(300,“groceries”)

clothing = Category(‘clothing’)
clothing.deposit(1000,“clothes initial deposit”)
clothing.withdraw(20,“pants”)
food.transfer(200,clothing)
clothing.ledger
This is the output I got :
[’{“amount”: 1000, “description”: food initial deposit}’,
‘{“amount”: -300, “description”: groceries}’,
‘{“amount”: 1000, “description”: clothes initial deposit}’,
‘{“amount”: -20, “description”: pants}’,
‘{“amount”: -200, “description”: Transfer to clothing}’,
‘{“amount”: 200, “description”: Transfer from food}’]

While this is the output expected:
[’{“amount”: 1000, “description”: clothes initial deposit}’,
‘{“amount”: -20, “description”: pants}’,
‘{“amount”: 200, “description”: Transfer from food}’]

Your code so far
class Category():

def __init__(self,category,balance=0,ledger=[],st_ledger=""):
    self.category = category
    self.balance = balance
    self.ledger = ledger
    self.st_ledger = st_ledger

def check_funds(self,amt):
    if amt > self.balance:
        return False
    else:
        return True


def deposit(self, dep_amt, description=""):
    self.balance +=dep_amt
    dep_note = "{\"amount\": "+str(dep_amt)+", \"description\": "+description+"}"
    self.ledger.append(dep_note)
    self.st_ledger = dep_note+self.st_ledger
    
def withdraw(self, wd_amt, description=""):
    if not self.check_funds(wd_amt):
        return False
    else:
        self.balance -= wd_amt
        wd_note = "{\"amount\": "+"-"+str(wd_amt)+", \"description\": "+description+"}"
        self.ledger.append(wd_note)
        self.st_ledger = wd_note+self.st_ledger
        return True
    
def get_balance(self):
    return self.balance

def transfer(self,tf_amt,category):
    wd_description = "Transfer to "+category.category
    dp_description = "Transfer from "+self.category
    self.withdraw(tf_amt,wd_description)
    category.deposit(tf_amt,dp_description)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0.

Challenge: Budget App

Link to the challenge:

That’s because parameters in python are evaluated just once when function/method is defined. This means when mutable data type is used as default value, it will be using the single list, which can be later mutated, instead of creating new one every time function/method is called.

OK, thanks. I think I figure out how to fix it

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.