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

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


慕哥6287543
浏览 137回答 2
2回答

呼如林

我想你已经很接近了!您不需要在构造函数方法中使用这些括号。我删除了那些。要打印出整个配方,我们可以简单地使用 to string 函数。根据需要更改它: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 minutesHere are the steps involved:Step 1: Bring water to boilStep 2: add broth
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python