创建对象列表的最佳方法?
Best way to create a list of objects?
food_data
是一个包含 JSON 数据的变量。使用这些数据,我想创建一个 Food 对象列表,就像这样
foods = []
for data_row in food_data:
foods.append(Food(data_row))
这是我的食物 class 目前的样子:
class Food(dict):
""" by inheriting from dict, Food objects become automatically serializable for JSON formatting """
def __init__(self, data):
""" create a serialized food object with desired fields """
id = data["id"]
name = data["title"]
image = data["image"]
super().__init__(self, id=id, name=name, image=image)
这里是一些示例数据:
[
{
"id": 738290,
"title": "Pasta with Garlic, Scallions, Cauliflower & Breadcrumbs",
"image": "https://spoonacular.com/recipeImages/716429-312x231.jpg",
},
{
"id": 343245,
"title": "What to make for dinner tonight?? Bruschetta Style Pork & Pasta",
"image": "https://spoonacular.com/recipeImages/715538-312x231.jpg",
}
]
有没有我可以为食物 class 编写的方法,它将获取数据和 return 自身不同版本的列表?
我将从 not subclassing dict
开始:有一种更好的方法可以使 Food
的实例可序列化。
接下来,make Food.__init__
dumb: 三个参数,用于设置三个属性。
然后,定义一个class方法,负责解析任意一个dict
,至少有id
、title
、image
键获得 Food.__init__
.
期望的值
最后,定义一个方法,将 Food
的实例转回 dict
(尽管不一定与 from_dict
使用的 dict
相同;生成一个序列化你想要的方式)。
class Food:
def __init__(self, id, name, image):
self.id = id
self.name = name
self.image = image
@classmethod
def from_dict(cls, d):
return cls(id=d['id'], name=d['title'], image=d['image'])
def to_dict(self):
return dict(id=self.id, name=self.name, image=self.image)
foods = [Food.from_dict(d) for d in food_data]
要使您的实例可序列化,请定义一个使用您的 to_dict
方法的客户编码器,
class FoodEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Food):
return obj.to_dict()
return super().default(obj)
这搭载了默认编码器;如果直接对象是 Food
、default
returns 可序列化 dict
。否则,它遵从其父级尝试对其进行序列化。
然后在对 json.dumps
的调用中使用 class。
print(json.dumps(foods, cls=FoodEncoder))
我认为我的代码可能过度设计了。但是我收到了很多在其他方面确实帮助了我的回复,所以我将在这里提供它们:
@娟帕
使用列表理解
foods = [Food[data] for data in food_data]
@Chepner - 无关但有用
subclass json.JSONEncoder 而不是 dict 的可序列化性
@马蒂亚斯
在 class 到 return 对象列表
内创建静态方法
@staticmethod
def create_foods(food_data):
foods = []
for data_row in food_data:
foods.append(Food(data_row))
food_data
是一个包含 JSON 数据的变量。使用这些数据,我想创建一个 Food 对象列表,就像这样
foods = []
for data_row in food_data:
foods.append(Food(data_row))
这是我的食物 class 目前的样子:
class Food(dict):
""" by inheriting from dict, Food objects become automatically serializable for JSON formatting """
def __init__(self, data):
""" create a serialized food object with desired fields """
id = data["id"]
name = data["title"]
image = data["image"]
super().__init__(self, id=id, name=name, image=image)
这里是一些示例数据:
[
{
"id": 738290,
"title": "Pasta with Garlic, Scallions, Cauliflower & Breadcrumbs",
"image": "https://spoonacular.com/recipeImages/716429-312x231.jpg",
},
{
"id": 343245,
"title": "What to make for dinner tonight?? Bruschetta Style Pork & Pasta",
"image": "https://spoonacular.com/recipeImages/715538-312x231.jpg",
}
]
有没有我可以为食物 class 编写的方法,它将获取数据和 return 自身不同版本的列表?
我将从 not subclassing dict
开始:有一种更好的方法可以使 Food
的实例可序列化。
接下来,make Food.__init__
dumb: 三个参数,用于设置三个属性。
然后,定义一个class方法,负责解析任意一个dict
,至少有id
、title
、image
键获得 Food.__init__
.
最后,定义一个方法,将 Food
的实例转回 dict
(尽管不一定与 from_dict
使用的 dict
相同;生成一个序列化你想要的方式)。
class Food:
def __init__(self, id, name, image):
self.id = id
self.name = name
self.image = image
@classmethod
def from_dict(cls, d):
return cls(id=d['id'], name=d['title'], image=d['image'])
def to_dict(self):
return dict(id=self.id, name=self.name, image=self.image)
foods = [Food.from_dict(d) for d in food_data]
要使您的实例可序列化,请定义一个使用您的 to_dict
方法的客户编码器,
class FoodEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Food):
return obj.to_dict()
return super().default(obj)
这搭载了默认编码器;如果直接对象是 Food
、default
returns 可序列化 dict
。否则,它遵从其父级尝试对其进行序列化。
然后在对 json.dumps
的调用中使用 class。
print(json.dumps(foods, cls=FoodEncoder))
我认为我的代码可能过度设计了。但是我收到了很多在其他方面确实帮助了我的回复,所以我将在这里提供它们:
@娟帕 使用列表理解
foods = [Food[data] for data in food_data]
@Chepner - 无关但有用 subclass json.JSONEncoder 而不是 dict 的可序列化性
@马蒂亚斯 在 class 到 return 对象列表
内创建静态方法@staticmethod
def create_foods(food_data):
foods = []
for data_row in food_data:
foods.append(Food(data_row))