为什么我能';我不能将python类保存到JSON文件中吗?

为什么我能';我不能将python类保存到JSON文件中吗?,python,json,python-3.x,class,Python,Json,Python 3.x,Class,我在做一个费用追踪器。我创建了一个Account类,用于注册特定的预算。所有帐户都保存在预算列表中。然后,我尝试使用save函数将预算列表保存到json文件中,该函数返回一个错误。这有点明显,但我想不出任何有效的替代方案。有解决办法吗?PD:我删除了所有与问题无关的结构,因为它已经工作了,而且不允许我发送所有代码。对不起,如果有什么事情似乎不符合上下文 def initialize(filename): """ Adjusts the starting parameters.

我在做一个费用追踪器。我创建了一个Account类,用于注册特定的预算。所有帐户都保存在预算列表中。然后,我尝试使用save函数将预算列表保存到json文件中,该函数返回一个错误。这有点明显,但我想不出任何有效的替代方案。有解决办法吗?PD:我删除了所有与问题无关的结构,因为它已经工作了,而且不允许我发送所有代码。对不起,如果有什么事情似乎不符合上下文

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")

我真的不确定我的解决方案,但是!!!如果我没记错的话,你 只能序列化json中的字典,因此可以尝试以下方法:

def保存(文件名、预算):
“”“保存对帐户所做的更改”“”
打开(文件名为“w”)作为f_obj:
budgets2=[预算中的预算
json.dump(预算2,f_obj)

您可以添加错误并进行回溯吗?
f_obj.write(json.dump(预算))
请参阅
json
模块的文档,了解如何教
json.dumps
如何序列化自定义类的实例。据我所知,只有当文件不存在时,
initialise
函数才会返回某些内容…实际上,当将旧会话中的dict加载到acc类中时,它也会以相反的方式返回。谢谢!:)