给定以下类定义:
class Food:
def __init__(self, name, taste):
self.name = name
self.taste = taste
编写一个以食品列表为参数的函数createFood()
,并为每个食品创建一个class Food
实例。然后,它返回已创建的实例列表。
作为参数传递给createFood()
的列表中的每个食品项目都是('name', 'taste')
形式的元组,因此食品项目列表可能如下所示:
[('curry', 'spicy'), ('pavlova', 'sweet'), ('chips', 'salty')]
函数createFood()
接受每个元组的两个元素,并将它们传递给食品的初始化器。然后,它收集初始化器返回的对象,并将它们添加到createFood()
返回的列表中。
不要调用该函数
发布于 2020-06-14 11:17:41
完全按照问题的要求去做:
编写一个函数createFood(),该函数将食品列表作为参数,并为每个食品创建一个类的实例。然后,它返回已创建的实例列表。
def createFood(fooditems):
"""takes a list of food items as argument and creates an instance
of class Food for each of them. It then returns the list of instances
that it has created.
"""
return [Food(name, taste) for name, taste in fooditems]
createFood([('curry', 'spicy'), ('pavlova', 'sweet'), ('chips', 'salty')])
https://stackoverflow.com/questions/62366833
复制相似问题