排序对象列表python。对象与我排序的对象不同

时间:2018-02-13 23:34:42

标签: python

我看过类似的问题,但我似乎无法弄清楚这一点。我有两个类,我的Item类,然后是我的Receipt类。在Receipt中,我有一个方法read_file,它逐行读取.txt文件,将其拆分。然后我将一个Item对象追加到我的列表中,这样我就有了一个Item对象列表。我试图按价格对此列表进行排序,但我不断得到" AttributeError:type object' Item'没有属性'价格'"我尝试了一些不同的东西,并在StackOverflow上查看类似的答案,但我似乎无法弄明白。根据我的理解,因为它看的是课而不是实例?感谢任何帮助,谢谢。

实际错误如下:

Error message : items.sort(key=operator.attrgetter('price'),reverse=False)
AttributeError: type object 'Item' has no attribute 'price'

我的代码:

import operator
import sys
class Item(object):
    def __init__(self, category, name, quantity, price):
        self.category = category
        self.name = name
        self.quantity = quantity
        self.price = price

    def getPrice(self):
        return self.price;

class Receipt(object):
    def __init__(self):
        pass

    def read_file(self):
        with open('grocery.txt') as file:
            items = [Item]
            for line in file:
                c,n,q,p = line.rstrip('\n').split(" ")
                items.append(Item(c,n,q,float(p)))
        return items

    def ask_receipt_format(self):
        answer = input("How would you like this receipt printed? (P for by price, C for by category, A for alphabetical order)")

        if answer.capitalize() == 'P':
            answer = 'P'
        elif answer.capitalize() == 'C':
            answer = 'C'
        elif answer.capitalize() == 'A':
            answer = 'A'
        else:
            print("You must choose a valid receipt format!\n")
            self.ask_receipt_format()
        return answer

    def calculate_total(self):
        pass

def print_bill(self, receipt_format,items):

    if receipt_format == 'P':
        print("Receipt by price")
        print("Category    Item            Quantity    Price    Sub-Total")
        items.sort(key=operator.attrgetter('price'),reverse=False)
        for n in range(len(items)):
            print("{:d} {0:4} {:d} {:4d} {:5d}".format(items[n].category,items[n].name,items[n].quantity,items[n].price, float(items[n].quantity) * float(items[n].price)))




def API(self):
    self.print_bill(self.ask_receipt_format(),self.read_file())


def main():
    receipt = Receipt()
    receipt.API()


if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:4)

观看以下片段:

def read_file(self):
    with open('grocery.txt') as file:
        items = [Item]

您在列表中放置的第一件事是类本身,它没有属性price。属性仅在类的实例中传递。相反,您希望将列表声明为空:items = []