为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥6287543 2021-08-14 17:02:37
我一直在学习 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 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

我想你已经很接近了!您不需要在构造函数方法中使用这些括号。我删除了那些。要打印出整个配方,我们可以简单地使用 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 minutes

Here are the steps involved:

Step 1: Bring water to boil

Step 2: add broth


查看完整回答
反对 回复 2021-08-14
  • 2 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号