I've seen similar questions but I just can't seem to figure this out. I have two classes, my Item class, and then my Receipt class. In Receipt I have a method read_file that reads a .txt file line by line, splitting it. I then append an Item object onto my list such that I have a list of Item objects. I'm trying to sort this list by price but I keep getting "AttributeError: type object 'Item' has no attribute 'price'" I've tried a few different things, and looked at similar answers on StackOverflow but I just can't seem to figure it out. From what I understand it's because it's looking at the class instead of the instance? Any help is appreciated, thank you.
The actual error is as follows:
Error message : items.sort(key=operator.attrgetter('price'),reverse=False)
AttributeError: type object 'Item' has no attribute 'price'
And my code:
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()