python将类对象作为参数传递

时间:2020-06-13 23:47:22

标签: function class tuples

给出以下类定义:

 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()接受每个元组的两个元素,并将它们传递给Food的初始化程序。然后,它收集初始化程序返回的对象,并将它们添加到createFood()返回的列表中。

请勿调用该函数

1 个答案:

答案 0 :(得分:0)

完全按照问题的要求进行

编写一个函数createFood(),该函数将食物列表作为参数并为每个食物创建一个Food类的实例。然后,它返回已创建的实例的列表。

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')])
相关问题