我见过类似的问题,但我似乎无法弄明白。我有两个类,我的 Item 类,然后是我的 Receipt 类。在收据中,我有一个 read_file 方法,它逐行读取 .txt 文件,并将其拆分。然后,我将一个 Item 对象附加到我的列表中,这样我就有了一个 Item 对象列表。我试图按价格对这个列表进行排序,但我不断收到“AttributeError: type object 'Item' has no attribute 'price'”我尝试了一些不同的东西,并在 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()
最佳答案
查看以下代码段:
def read_file(self):
with open('grocery.txt') as file:
items = [Item]
您放入列表的第一件事是类本身,它没有属性 price
。属性只在类的实例中传递。相反,您想将列表声明为空:items = []
。
关于python - 排序对象列表python。对象与我正在分类的对象属于不同的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48777411/