I'm taking a course on freecodecamp.org on scientific-computing-with-python and I'm stuck. The course describes objects and interactions with them rather sparingly, but the problem requires transferring data from one object to another, which takes me away from standard OOP understandings. Here, if anything, is a link to the task:
In it, we are making a program for accounting for purchased items. And it needs to have a "transfer" method that takes a value and a category name as input and sends that value to the right category. The problem is that we need to specify a link to this category, and not just a link to an already existing one, but a link automatically generated by the name of the entered category. The question is, how do we do that?
My code looks like this:
class Category:
def __init__(self, categories):
self.categories = categories
self.ledger = []
def deposit(self, amount, description=""):
self.ledger.append({"amount": amount, "description": description})
def withdraw(self, amount, description=""):
self.ledger.append({"amount": -amount, "description": description})
def get_balance(self):
return self.ledger[0]["amount"] self.ledger[1]["amount"]
def transfer(self, amount, categories):
self.categories.ladger.append({"amount": amount, "description": f"Transfer to {categories}"})
I am trying my best to expand my knowledge of OOP, but I have a feeling that the problem must be solved in an insanely simple way. Perhaps "ledger" should be made a global attribute, but then there is a problem with indexing algorithms. Another option is to link in the way strings are joined, but so far I don't understand how to make a link from strings.
CodePudding user response:
Minimal example for the transfer as I understand it from the task (not full solution of the task):
class Category:
def __init__(self, name):
self.name = name #renamed for clarity
self.ledger = []
def deposit(self, amount, description=""):
self.ledger.append({"amount": amount, "description": description})
def withdraw(self, amount, description=""):
self.ledger.append({"amount": -amount, "description": description})
def transfer(self, other, amount):
self.withdraw(amount, f"Transfer to {other.name}")
other.deposit(amount, f"Tranfer from {self.name}")
This would be the minimal setup. The program so far would then e.g. be:
food = Category('food')
clothing = Category('clothing')
food.transfer(clothing, 100)
print(food.ledger)
print(clothing.ledger)
This would first create the two categories and then transfer 100 from food
to clothing
.