我可能会建议考虑创建一个类并使用 OOP 来代替类似的东西。
class Recipe:
def __init__(self,name,ingredients):
self.name = name
self.ingredients = ingredients
def __str__(self):
return "{name}: {ingredients}".format(name=self.name,ingredients=self.ingredients)
toast = Recipe("toast",("bread"))
sandwich = Recipe("sandwich",("bread","butter","ham","cheese","butter","bread"))
随着您的“模板”变得越来越复杂,它不仅仅是一个数据定义,还需要逻辑。使用类将允许您封装它。
例如,我们的三明治上面有 2 个面包和 2 个黄油。我们可能希望在内部跟踪这一点,如下所示:
class Recipe:
def __init__(self,name,ingredients):
self.name = name
self.ingredients = {}
for i in ingredients:
self.addIngredient(i)
def addIngredient(self, ingredient):
count = self.ingredients.get(ingredient,0)
self.ingredients[ingredient] = count + 1
def __str__(self):
out = "{name}: \n".format(name=self.name)
for ingredient in self.ingredients.keys():
count = self.ingredients[ingredient]
out += "\t{c} x {i}\n".format(c=count,i=ingredient)
return out
sandwich = Recipe("sandwich",("bread","butter","ham","cheese","butter","bread"))
print str(sandwich)
这给了我们:
sandwich:
2 x butter
1 x cheese
1 x ham
2 x bread