<p>我在运行代码时没有发现任何问题(但是我不得不想象一下这个类,因为你没有给出它)。在</p>
<pre><code>class Food:
def __init__(self):
self.food_list = None
def totalCalorie(self):
for i in range(0, len(self.food_list)):
j = self.food_list[i][3]
j += j
print("Total calorie of all food is {}Kcal".format(j))
f = Food()
f.food_list = [['apple', 100, 'Fruit', 384.0], ['orange', 100, 'Fruit', 384.0]]
f.totalCalorie()
</code></pre>
<p>输出:“所有食物的总热量为768.0卡”</p>
<p>我用的是Python2.7</p>
<p><strong>编辑1:</strong></p>
<p>正如卢卡斯·安斯蒂格在你的帖子评论中指出的,“你的j+=j逻辑有一个缺陷”</p>
<p>您应该这样做:</p>
^{pr2}$
<p><strong>编辑2:</strong></p>
<p>现在我有了您的全部代码,我可以强调两个问题:</p>
<ol>
<li><p>您正在尝试对一个Food对象使用索引,但是您的Food对象不支持按您的方式构造索引,如果您确实想使用支持索引的对象,请阅读<a href="https://docs.python.org/2/reference/datamodel.html#emulating-container-types" rel="nofollow noreferrer">this (from doc)</a>或{a2}。
无论如何,您可以通过访问Food对象实例的属性“carorie”来轻松解决这个问题。所以<code>j += i[3]</code>变成{<cd2>},但它不会工作,因为(见第2点)</p></li>
<li><p>Input返回一个字符串,因此i.carrie是一个字符串,您必须执行<code>j += float(i.calorie)</code>否则将得到一个TypeError(与Javascript不同,Python不接受字符串和整数连接)</p></li>
</ol>
<p>最后,您的代码变成:</p>
<pre><code>class Food:
def __init__(self, name, quantity, category, calorie):
self.name = name
self.quantity = quantity
self.category = category
self.calorie = calorie
class FoodList:
def __init__(self):
self.food_list = []
def totalCalorie(self):
j = 0
for i in self.food_list:
j += float(i.calorie)
print("Total calorie of all food is {}Kcal".format(j))
def addFood(self, newfruit):
self.food_list.append(newfruit)
name = input("Name? ")
quantity = input("Quantity? ")
category = input("Category? ")
calorie = input("Calorie? ")
f = Food(name, quantity, category, calorie)
patient = FoodList()
patient.addFood(f)
name1 = input("Name? ")
quantity1 = input("Quantity? ")
category1 = input("Category? ")
calorie1 = input("Calorie? ")
f1 = Food(name1, quantity1, category1, calorie1)
patient.addFood(f1)
patient.totalCalorie()
</code></pre>
<p>输出:</p>
<pre><code>Name? apple
Quantity? 100
Category? Fruit
Calorie? 384.0
Name? Coq_au_vin
Quantity? 1
Category? Delicious_meal
Calorie? 142000.0
Total calorie of all food is 142384.0Kcal
</code></pre>
<p>我希望我在这方面有所帮助,但是,就像我在评论中说的,你真的应该读一些关于OOP的好材料,比如“headfirst”系列,或者如果你喜欢更具交互性的东西,Udemy上有很棒的课程和教程。在</p>