You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中动态创建Recipe类实例以添加多个食谱?

解决方案:用容器存储动态创建的食谱实例

你可以用列表或者字典来统一存储所有Recipe实例,这样就不用预定义meal1、meal2这类固定变量,每次选“添加食谱”时直接创建实例并塞进容器就行,管理起来也更方便。

推荐优化:拆分类的职责

先把原Recipe类里的用户输入逻辑抽出来,让类只负责存储数据——这样代码结构更清晰,后续扩展也更灵活:

class Recipe:
    def __init__(self, title, ingredients, instructions):
        self.title = title
        self.ingredients = ingredients  # 格式:{食材名称: 用量}
        self.instructions = instructions

    def __repr__(self):
        # 自定义实例打印格式,方便调试查看
        return f"Recipe(title='{self.title}', ingredients={self.ingredients})"

实现主菜单与动态添加逻辑

用一个列表存储所有食谱,再写个菜单循环让用户选择操作:

def collect_recipe_details():
    # 单独处理食材输入
    ingredients = {}
    while True:
        ingredient = input('输入食材名称,输"finish"结束添加:')
        if ingredient == 'finish':
            break
        amount = input(f"{ingredient}的用量是多少?")
        ingredients[ingredient] = amount
    
    title = input("请输入食谱名称:")
    instructions = input("请输入制作步骤:")
    return Recipe(title, ingredients, instructions)

def main():
    recipes = []  # 用列表存所有食谱实例
    while True:
        print("\n=== 每周备餐程序 ===")
        print("1. 添加新食谱")
        print("2. 查看所有食谱")
        print("3. 退出程序")
        choice = input("选个操作:")
        
        if choice == '1':
            new_recipe = collect_recipe_details()
            recipes.append(new_recipe)
            print(f"「{new_recipe.title}」添加成功!")
        elif choice == '2':
            if not recipes:
                print("还没添加任何食谱呢!")
                continue
            print("\n=== 已存食谱 ===")
            for idx, recipe in enumerate(recipes, 1):
                print(f"{idx}. 名称:{recipe.title}")
                print(f"   食材:{recipe.ingredients}")
                print(f"   步骤:{recipe.instructions}\n")
        elif choice == '3':
            print("拜拜!")
            break
        else:
            print("输入错了,重新选!")

if __name__ == "__main__":
    main()

核心要点

  • 容器存储:recipes列表可以动态添加任意数量的Recipe实例,不用提前定义一堆变量,所有实例都在一个地方管理。
  • 职责拆分:把输入逻辑放到单独的函数里,Recipe类只做数据封装,后续如果要改输入方式(比如从文件导入),只动那个函数就行。
  • 循环菜单:通过while True让程序一直运行,直到用户选退出。

如果不想改原来的Recipe类,直接用列表存实例也可以:

# 保留你原来的Recipe类
class Recipe:
    def __init__(self):
        ingredients = {}
        while True:
            ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
            if ingredient == 'finish':
                break
            amount = input("How much of this ingredient? ")
            ingredients[ingredient]=amount
        self.ingredients = ingredients
        self.title = input('What is the name of the recipe? ')
        self.instructions = input('Type out your recipe instructions; ')

def main():
    recipes = []
    while True:
        print("\n=== Meal Prep Program ===")
        print("1. Add Recipe")
        print("2. View All Recipes")
        print("3. Exit")
        choice = input("Enter your choice: ")
        
        if choice == '1':
            recipes.append(Recipe())
            print("Recipe added successfully!")
        elif choice == '2':
            if not recipes:
                print("No recipes added yet!")
                continue
            for i, recipe in enumerate(recipes, 1):
                print(f"\nRecipe {i}: {recipe.title}")
                print("Ingredients:", recipe.ingredients)
                print("Instructions:", recipe.instructions)
        elif choice == '3':
            print("Exiting program...")
            break
        else:
            print("Invalid choice, try again!")

if __name__ == "__main__":
    main()

内容的提问来源于stack exchange,提问作者William

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:46:05