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?
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())
Because in your
transfer()
function, you create a new Category each time. Even if the new category has the same name as an existing category, they are still two separate objects in memory. And you never use the newly created category anywhere.Instead of passing in a string and creating a new Category with that name, you could pass in an existing category.