[英]Why I can't save my python Class into a JSON file?
I'm making an expense tracker.我正在制作费用跟踪器。 I've created an Account class, that registers a specific budget.
我创建了一个 Account 类,用于注册特定的预算。 All the accounts are saved in a Budgets list.
所有帐户都保存在预算列表中。 Then I try to save the Budgets list into a json file using the save function, which returns an error.
然后我尝试使用 save 函数将预算列表保存到一个 json 文件中,该函数返回一个错误。 This is kinda obvious, but I can't think of any efficient alternative.
这有点明显,但我想不出任何有效的替代方法。 Any solution?
有什么解决办法吗? PD: I deleted all the structure not related with the problem, because it already works, and it doesn't let me send all the code.
PD:我删除了所有与问题无关的结构,因为它已经可以工作了,而且它不让我发送所有代码。 Sorry if something seems out of context.
对不起,如果有些事情似乎脱离了上下文。
def initialize(filename):
"""
Adjusts the starting parameters.
"""
budgets = []
try:
# Checks if the file exists, and executes the apropiate code
# according to the situation.
with open(filename, 'r') as f_obj:
budgets = json.load(f_obj)
# Loads the info from older sessions
# into the list.
except FileNotFoundError: #If the file doesn't exist, we create it.
print("Seems you are the first one here!")
return budgets
class Account:
"""
Simulates a budget with custom percentatges for each area of spending
"""
def __init__(self, name, cash, percent):
self.name = name
self.cash = int(cash)
self.percent = percent
self.budget = {}
for key, value in self.percent.items():
self.budget[key] = self.cash * value / 100
def save(filename, budgets):
"""Saves the changes made into the accounts"""
with open(filename, 'w') as f_obj:
json.dump(budgets, f_obj)
def main():
"""Executes the main program"""
filename = "budgets.json"
budgets = initialize(filename)
while True:
a = input("\nSelect the desired operation (h for help): ")
if a == 'help':
help()
elif a == 'save':
save(filename, budgets)
print('account saved succesfully')
elif a == 'exit':
break
else:
print("ERROR: The input is not an operation\n")
I am really not sure about my solution, but!!!我真的不确定我的解决方案,但是!!! If I remember correctly, you can only serialize dictionaries in json, so maybe try this out:
如果我没记错的话,你只能在 json 中序列化字典,所以也许试试这个:
def save(filename, budgets):
"""Saves the changes made into the accounts"""
with open(filename, 'w') as f_obj:
budgets2 = [budget.__dict__ for budget in budgets]
json.dump(budgets2, f_obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.