TypeError:“Food”对象不支持索引

2024-06-16 12:18:46 发布

您现在位置:Python中文网/ 问答频道 /正文

self.food_list = [['apple', 100, 'Fruit', 384.0], ['orange', 100, 'Fruit', 384.0]]

我想把索引3中的元素求和。 预期输出是Total calorie of all food is 768.0Kcal

^{pr2}$

但出现了以下错误:

Traceback (most recent call last):
  File "D:/PythonTim/Assignment/nutritionDriver.py", line 60, in <module> 
    main()
  File "D:/PythonTim/Assignment/nutritionDriver.py", line 43, in main
    patient.totalCalorie()
  File "D:\PythonTim\Assignment\nutritionApp.py", line 132, in totalCalorie
    j = self.food_list[i][3]
TypeError: 'Food' object does not support indexing

我想做的是当用户想合计列表中的所有卡路里时,系统将显示列表中的总卡路里。在

有别的办法吗?谢谢!在

编辑:

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 += i[3]
        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()

Tags: nameinselfinputfooddefquantitylist
2条回答

只需迭代食物清单的元素。 作为对罗宾爵士回答的改进:

class Food:
    food_list = []

    def totalCalorie(self):
        j=0
        for i in self.food_list:
            j += i[3]
        print("Total calorie of all food is {}Kcal".format(j))

    def addFood(self,newfruit):
        self.food_list.append(newfruit)


f = Food()
f.addFood(['banana', 100, 'Fruit', 100.0])
f.addFood(['orange', 100, 'Fruit', 384.0])
f.totalCalorie()

我也编辑了j +=部分,这样它也可以处理2个以上的元素。在

我在运行代码时没有发现任何问题(但是我不得不想象一下这个类,因为你没有给出它)。在

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()

输出:“所有食物的总热量为768.0卡”

我用的是Python2.7

编辑1:

正如卢卡斯·安斯蒂格在你的帖子评论中指出的,“你的j+=j逻辑有一个缺陷”

您应该这样做:

^{pr2}$

编辑2:

现在我有了您的全部代码,我可以强调两个问题:

  1. 您正在尝试对一个Food对象使用索引,但是您的Food对象不支持按您的方式构造索引,如果您确实想使用支持索引的对象,请阅读this (from doc)或{a2}。 无论如何,您可以通过访问Food对象实例的属性“carorie”来轻松解决这个问题。所以j += i[3]变成{},但它不会工作,因为(见第2点)

  2. Input返回一个字符串,因此i.carrie是一个字符串,您必须执行j += float(i.calorie)否则将得到一个TypeError(与Javascript不同,Python不接受字符串和整数连接)

最后,您的代码变成:

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()

输出:

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

我希望我在这方面有所帮助,但是,就像我在评论中说的,你真的应该读一些关于OOP的好材料,比如“headfirst”系列,或者如果你喜欢更具交互性的东西,Udemy上有很棒的课程和教程。在

相关问题 更多 >