Linked Questions

Popular Questions

How to implement the transfer method

Asked by At

I am trying to create a budget app that using python. I am using a class Category that can instantiate different budget categories.

I have a transfer and withdraw instance method and a transfer method. The problem is that when I use the transfer method, it doesn't reflect in the category transferred to. How can I go about this?

code

code output

class Category:
    def __init__(self, category):
        self.category = category
        self.ledger = []
    def deposit(self, amount, description=""):
        #self.amount = amount
        #self.description = description
        b = {"amount": amount, "description": description}
        self.ledger.append(b)
    def withdraw(self, amount, description=""):
        amount = amount * -1
        #self.description = description
        self.ledger.append({"amount": amount, "description": description})
    def get_balance(self):
        balance = 0
        for i in self.ledger:
            balance = balance + i["amount"]
        return(balance)
    def transfer(self, amount, new_category):
        self.withdraw(amount, f"Transfer to {new_category}")
        Category(new_category).deposit(amount, f"Transfer from {self.category}")
    def __str__(self):
        return(f"This is the budget for {self.category}")
    
    
food = Category("food")
housing = Category("housing")
food.deposit(200, "lunch")
food.withdraw(400, "Indomie")
food.transfer(480, "housing")
print(food)
print(food.ledger)
print(food.get_balance())
print(housing.ledger)
print(housing.get_balance())

Related Questions