【发布时间】:2021-11-24 03:41:22
【问题描述】:
我正在制作一个应用程序,让您可以登录或创建餐厅。作为餐厅老板,您可以添加/删除/编辑冰箱。我的最终目标是我有一个餐厅列表,我会写入一个 JSON 文件,并且每当我重新运行应用程序时,我都可以将这些数据拉入并模拟“成为餐厅老板”并编辑冰箱选择的餐厅。
我基本上想要这个:
data = {
restaurants: [
{
restaurant: {
name: "Peppy",
pw: "123",
fridges: [
{
fridge: {
owner: restaurant.name,
contents: []
}
}
]
}
}
]
}
我有以下两个类(显示相关方法):
class Restaurant:
def __init__(self, owner, password):
self.__password = password
self.owner = owner
self.__owned_fridges = [] # list of owned fridges
def add_fridge(self):
nickname = input("What would you like to name the fridge: ")
self.__owned_fridges.append(fr(self.owner, nickname))
print("Fridge added!")
class Fridge:
def __init__(self, owner, nickname):
self.nickname = nickname
self.owner = owner
self.__authorized_users = [owner]
self.__contents = []
def add_to_fridge(self):
if len(self.__contents) == 5:
print("Your fridge is full!")
else:
item = input("What would you like to add : ")
self.__contents.append(item)
我的问题是为 JSON 序列化这个。我发现以下方法可以将餐厅对象序列化为 JSON,但不能将嵌套的冰箱对象序列化:
data = {
'restaurants': []
}
# Testing code
test = res("Jac", "350b534")
test.add_fridge()
test.add_fridge()
data['restaurants'].append(json.dumps(test.__dict__))
我对python比较陌生,而且我来自js背景,所以我对语法还是很熟悉的。我的问题是,如何序列化冰箱的内部列表?
【问题讨论】:
-
嗯,看起来像
nickname和authorized_users这样的一些字段将从序列化中排除,因为我在结果字典中看不到它们。