The Price of a Line
A receipt also shows how much each line costs: the price of one piece times the quantity. Two loaves of bread at $3 each cost $6.
The price of a line belongs to the item, so it will be a method of the class Item: line_total(). Like every method, it gets the object it was called on as self, so it can read self.price and self.quantity and return their product. You call it on an item: item.line_total(). Why a method for a single multiplication? You'll need the price of a line in several places: on the receipt, in the total and, later, for sorting. And a good name says what the code means: item.line_total() is easier to understand than item.price * item.quantity.
Then the item will show its own line. Remember __str__ from the lesson on classes: when a class has it, print() shows the text it returns. And inside a method, you call another method of the same object with self. in front:
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def minutes(self):
return self.pages * 2
def __str__(self):
return f"{self.title}: {self.minutes()} minutes"
book = Book("Matilda", 240)
print(book)Matilda: 480 minutesWithout self., Python looks for an ordinary function called minutes, and the program ends with an error that even suggests the fix: NameError: name 'minutes' is not defined. Did you mean: 'self.minutes'? Also, __str__ must return the text. One that prints it instead returns None, and print(book) ends with TypeError: __str__ returned non-string (type NoneType).
Write the methods inside the class, indented as much as __init__, with an empty line between them. Once the item has __str__, print_receipt() doesn't need to know what a line looks like: print(item) is enough.
Instructions
- 1
In the class
Item, under__init__, write a methodline_total()that returns the price of one piece times the quantity. Then, inprint_receipt(), add the price of the line to the end of each line, withitem.line_total():Bread: 2 x $3 = $6. - 2
Now let the item show its line. Under
line_total(), write a method__str__that returns the same line (in the class, it'sselfinstead ofitem). Inprint_receipt(), print each item with justprint(item). The receipt stays the same.