python - 创建新对象时可以使用列表作为属性吗?
问题描述
我一直在学习 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.]
解决方案
让一个类包含一个食谱对我来说很有意义,但我更喜欢一个类来包含我所有的食谱:
class Recipes:
def __init__(self):
self.recipes = {}
def add_recipes(self, to_add):
for key in to_add:
self.recipes[key] = to_add[key]
def display_recipe(self, name):
recipe = self.recipes[name]
print("Name: ",name)
print("Ingredients: ", *recipe["ingredients"])
print("Cook time: ", recipe["cooktime"])
r = Recipes()
r.add_recipes({"Chicken Noodle": {"ingredients": ["Broth", "noodles"], "cooktime": "7 minutes"}})
r.display_recipe("Chicken Noodle")
您的代码中有一些错误:
Chicken Noodle = Recipe(Chicken Noodle, [Broth, noodles], 7 minutes, [Bring water to boil, add broth, etc.]
需要变成:
ChickenNoodle = Recipe("Chicken Noodle", ["Broth", "noodles"], "7 minutes", ["Bring water to boil", "add broth, etc."])
类定义也需要稍作改动,以符合常规风格和一些语法规则:
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
推荐阅读
- python - 数据流作业在 BigQuery 写入失败并出现后端错误
- javascript - Mongodb Group 并从文档中获取其他字段
- java - 检查一个项目是否是一个特定的 ArrayList,而不是一个具有相等值的项目
- laravel - 如何加载与 { json:api } 客户端的关系?
- .net - WireMock 中 STARTED 的 .NET 等价物是什么?
- python - Plotly:如何使用 updatemenus 更新一个特定的跟踪?
- c# - Xamarin.Forms StackLayout 分为 3 列
- c - 调试器在哪里保存指向代码段中下一个命令的指针?
- json - OpenApi 是否有通用文件规范?
- java - 如果后端是 URL,则从客户端到后端的 API 流