首页 > 解决方案 > 创建新对象时可以使用列表作为属性吗?

问题描述

我一直在学习 python,并想开始我的第一个项目,我今天完成了关于课程的学习,并想努力理解算法,以及我所学的一切如何结合在一起。我想这样做是因为我觉得这些在线资源为您提供了很好的信息,但并没有教太多关于将这些概念应用于项目的内容。

我想做一个简单的程序,我可以在其中输入食谱名称,并打印成分、烹饪时间、步骤和名称。我想为成分和步骤使用一个列表,并且我想以列表格式打印它们(可能包含在边框中)。这可能吗?

Class Recipe:
    def __init__(self, recipe_name, ingredients, cook_time, steps)
        (self.recipe_name = recipe_name)
        (self.ingredients = ingredients)
        (self.cook_time = cook_time)
        (self.steps = steps)

Chicken Noodle = Recipe(Chicken Noodle, [Broth, noodles], 7 minutes, [Bring water to boil, add broth, etc.]

标签: python

解决方案


让一个类包含一个食谱对我来说很有意义,但我更喜欢一个类来包含我所有的食谱:

class Recipes:
  def __init__(self):
    self.recipes = {}

  def add_recipes(self, to_add):
      for key in to_add:
          self.recipes[key] = to_add[key]

  def display_recipe(self, name):
    recipe = self.recipes[name]  
    print("Name: ",name)
    print("Ingredients: ", *recipe["ingredients"])
    print("Cook time: ", recipe["cooktime"])

r = Recipes()
r.add_recipes({"Chicken Noodle": {"ingredients": ["Broth", "noodles"], "cooktime": "7 minutes"}})
r.display_recipe("Chicken Noodle")

您的代码中有一些错误:

Chicken Noodle = Recipe(Chicken Noodle, [Broth, noodles], 7 minutes, [Bring water to boil, add broth, etc.]

需要变成:

ChickenNoodle = Recipe("Chicken Noodle", ["Broth", "noodles"], "7 minutes", ["Bring water to boil", "add broth, etc."])

类定义也需要稍作改动,以符合常规风格和一些语法规则:

class Recipe:
    def __init__ (self, recipe_name, ingredients, cook_time, steps):
        self.recipe_name = recipe_name
        self.ingredients = ingredients
        self.cook_time = cook_time
        self.steps = steps

推荐阅读