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
添加回答
举报