【问题标题】:python pass class object as argumentpython将类对象作为参数传递
【发布时间】:2020-06-13 23:47:22
【问题描述】:

给定以下类定义:

 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() 返回的列表中。

不要调用函数

【问题讨论】:

    标签: function class tuples


    【解决方案1】:

    完全按照问题要求做:

    编写一个函数 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')])
    

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-10
      • 2012-03-30
      相关资源
      最近更新 更多