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

Python咖啡师训练器项目:动态问题输入与变量赋值难题

解决方案

方法一:用列表收集答案(适合问题顺序固定的场景)

  1. 收集所有用户答案
    把每次输入的答案存入列表,避免循环中覆盖变量:

    questions = Questions.get_questions(recipe_label.lower())
    answers = []
    # 直接遍历问题列表,写法更简洁
    for question in questions:
        user_answer = input(question)
        answers.append(user_answer)
    
  2. 传入Recipe_Factory
    用*解包列表,把所有答案作为可变参数传入工厂方法:

    recipe = Recipe_Factory.get_recipe(recipe_label, size_label, hot_label, *answers)
    

    对应的Recipe_Factory.get_recipe需要接受可变位置参数,示例定义:

    class Recipe_Factory:
        @staticmethod
        def get_recipe(recipe_label, size_label, hot_label, *additional_args):
            # 按顺序读取参数,比如additional_args[0]是第一个问题的答案
            foam_amount = additional_args[0]
            syrup_type = additional_args[1]
            # 后续逻辑:用这些参数构建食谱对象
            return Recipe(...)
    

方法二:用字典收集答案(更直观,适合对应明确参数名的场景)

如果能调整Questions.get_questions让它返回参数名:问题文本的字典(比如{"foam_amount": "请输入奶泡量:", "syrup_type": "请选择糖浆种类:"}),可以用字典存储答案,避免依赖顺序:

  1. 收集带参数名的答案

    questions = Questions.get_questions(recipe_label.lower())
    answers = {}
    for param_name, question_text in questions.items():
        answers[param_name] = input(question_text)
    
  2. 传入Recipe_Factory
    用**解包字典,把键值对作为关键字参数传入:

    recipe = Recipe_Factory.get_recipe(recipe_label, size_label, hot_label, **answers)
    

    对应的工厂方法定义:

    class Recipe_Factory:
        @staticmethod
        def get_recipe(recipe_label, size_label, hot_label, **kwargs):
            # 直接通过参数名取值,更清晰
            foam_amount = kwargs.get("foam_amount")
            syrup_type = kwargs.get("syrup_type")
            # 构建食谱逻辑
            return Recipe(...)
    

注意事项

  • 确保Recipe_Factory.get_recipe的参数定义和你传入的答案数量/类型匹配
  • 如果问题顺序可能变化,优先用字典方式,避免参数对应错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:45:42