Dataclasses
Completed
Use @dataclass to create Item(name: str, price: float, qty: int = 1) with a method total(). Read items name price qty, print each item (dataclasses get a __repr__ for free) and then the grand total with 2 decimals.
Input
Line 1: n. Then n lines.
Output
n + 1 lines.
Example
Input
2 pen 1.5 4 book 12 1
Output
Item(name='pen', price=1.5, qty=4) Item(name='book', price=12.0, qty=1) 18.00
Editor
Python
Hints
@dataclass writes __init__, __repr__ and __eq__ from the annotated fields.
Solution explanation
Dataclasses remove the boilerplate from classes that mainly hold data.
Show solution
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float
qty: int = 1
def total(self):
return self.price * self.qty
items = []
for _ in range(int(input())):
name, price, qty = input().split()
items.append(Item(name, float(price), int(qty)))
print(items[-1])
print(f"{sum(i.total() for i in items):.2f}")