【发布时间】:2021-11-14 01:03:47
【问题描述】:
TLDR - 我想将一些变量保存到 JSON 文件中。其中一些是属于自定义类的对象列表。由于 JSON 无法序列化它们,因此会引发错误。我该怎么做?
我正在做一个简单的基于文本的顶级王牌程序,其中相关类如下:
Player(以下子类)
人类
人工智能
卡片
我只编写了大约 3 个月的代码。我的项目代码本身是完全正常的,但我在开始时实现了一个加载选项,在每一轮结束时实现了一个保存选项。
下面是我的配置模块,它包含其他模块访问的所有变量,并包含保存/加载所需的所有内容。
import json
#All variables that need to be accessed between various modules publicly
total_players = 0
players = []
dead_players = []
num_of_humans = 0
num_of_ai = 0
total_cards = 0
cards = []
def save_file():
save_name = input("Save name (You will use this to load) > ")
path = 'path_to_dir{0}.json'.format(save_name)
data = {
'total_players' : total_players,
'players' : players,
'dead_players' : dead_players,
'num_of_humans' : num_of_humans,
'num_of_ai' : num_of_ai,
'total_cards' : total_cards,
'cards' : cards
}
with open(path, 'w+') as f:
json.dump(data, f)
def load_file():
load_name = input(f"Enter the name of your save > ")
path_two = 'path_to_dir{0}.json'.format(load_name)
with open(path_two, 'r') as f:
sf = json.load(f)
total_players = str(sf['total_players'])
players = str(sf['players'])
dead_players = str(sf['dead_players'])
num_of_humans = str(sf['num_of_humans'])
num_of_ai = str(sf['num_of_ai'])
total_cards = str(sf['total_card'])
cards = str(sf['cards'])
这些变量的说明:
total_players 是整数形式的玩家总数
玩家是属于 Human 或 Ai 类的对象列表
dead_players 同上
(下面自解释)
num_of_humans 是整数
num_of_ai 是 int
总卡数是 int
Cards 是 Card 类的对象列表
我的目标是存储所有这些变量的状态,并能够将它们相应地加载到顶部的变量中。在当前状态下,JSON 无法序列化我的自定义类的对象。
【问题讨论】: