我定义了一个叫做食物的类,其参数是卡路里,钠,钾,碳水化合物,纤维,糖,蛋白质,va,vc,钙和铁。然后我可以在这个课上创造食物,如英国黄瓜,蟹棒,海草和糙米。我希望在食品类中有一个用户定义的功能或方法,它允许我将这些食物组合在一起以创建一种名为California roll的新食物,并计算这种新食物的所有属性。
class Food:
def __init__(self, name, cal, fat, sod, pot, carbs, fiber, sugar, protein, va, vc, calcium, iron, unit):
self.name = name
self.cal = cal
self.fat = fat
self.sod = sod
self.pot = pot
self.carbs = carbs
self.fiber = fiber
self.sugar = sugar
self.protein = protein
self.va = va
self.vc = vc
self.calcium = calcium
self.iron = iron
englishcucumber = Food('English Cucumber', 15, 0, 2, 147, 2, 0.5, 1.7, 0.7, 2, 5, 2, 2,1)
brownrice = Food("Brown Rice", 1440, 12, 80, 0, 312, 16, 8, 32, 0, 0, 0, 10, 4)
crabstick = Food("Crab Stick", 33, 0, 116.7, 0, 4.7, 1.3, 0, 4, 0, 0.33, 0.33, 0, 2)
seawead = Food("Sea Wead", 10, 0, 0, 0, 1, 1, 0, 1, 6, 4, 0, 3, 1)
我已经定义了一个对象,我该如何组合这些对象?有没有什么方法可以定义一个函数,其输入变量是对象而不仅仅是正常变量?
答案 0 :(得分:0)
试试这个:
class Food:
def __init__(self, name, cal, fat, sod, pot, carbs, fiber, sugar, protein, va, vc, calcium, iron, unit):
self.name = name
self.cal = cal
self.fat = fat
self.sod = sod
self.pot = pot
self.carbs = carbs
self.fiber = fiber
self.sugar = sugar
self.protein = protein
self.va = va
self.vc = vc
self.calcium = calcium
self.iron = iron
def combine(self, name, other):
"""Given a name and another class instance of food, return a food instance with all of the values combined."""
r = Food(name, cal=self.cal+other.cal, fat=self.fat+other.fat, sod=self.sod+other.sod, pot=self.pot+other.pot, carbs=self.carbs+other.carbs, fiber=self.fiber+other.fiber, sugar=self.sugar+other.sugar, protein=self.protein+other.protein, va=self.va+other.va, vc=self.vc+other.vc, calcium=self.calcium+other.calcium, iron=self.iron+other.iron, unit=self.unit+other.unit)
return r