创建新对象时,可以使用列表作为属性吗?

时间:2018-11-11 02:53:19

标签: python

我一直在学习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.]

2 个答案:

答案 0 :(得分:0)

让一个班级包含一个食谱对我来说很有意义,但我希望一个班级包含我所有的食谱:

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

答案 1 :(得分:0)

我认为您非常接近!您无需在构造函数方法中使用这些括号。我删除了那些。要打印出整个配方,我们可以简单地使用to字符串功能。根据需要进行更改:

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


    def __str__(self):
      output = ''
      output += 'Here is the recipe for {}:\n'.format(self.recipe_name)
      output += 'You will need: {}\n'.format(self.ingredients)
      output += 'This recipe takes: {}\n'.format(self.cook_time)
      output += 'Here are the steps involved:\n'

      for i, step in enumerate(self.steps):
        output += 'Step {}: {}\n'.format(i + 1, step)

      return output

您可以运行以下代码:

chicken_noodle = Recipe('Chicken Noodle', ['Broth', 'noodles'], '7 minutes', ['Bring water to boil', 'add broth'])

print (chicken_noodle)

输出:

Here is the recipe for Chicken Noodle:
You will need: ['Broth', 'noodles']
This recipe takes: 7 minutes
Here are the steps involved:
Step 1: Bring water to boil
Step 2: add broth