Adding Transaction History
For many reasons, it's essential we track the transactions made in our store. Let's create a Transaction class to contain the details of each transaction that we processed in the previous tutorial.
class Transaction:
def __init__(
self.num_items: int,
self.original_price: float,
self.discounted_price: float = 0.0
) -> None:
self.num_items = num_items
self.original_price = original_price
self.discounted_price = discounted_price
Add a transactions attribute to the class, and update the sell method to use this object:
class Store:
def __init__(name: str, inventory: int, balance: float, price: float) -> None:
self.name = name
self.inventory = inventory
self.balance = balance
self.price = price
self.transactions = [] # Initialize an empty list to store transactions
def sell(self, num_items: int, discount: float = 0.0) -> None:
if num_items > self.inventory:
raise Exception("Not enough inventory to sell the requested number of items.")
transaction = Transaction(
num_items=num_items,
original_price=self.price,
discounted_price=self.price * (1 - discount)
)
self.transactions.append(transaction)
# Read num_items and price from the transaction object
self.inventory -= transaction.num_items
self.balance += transaction.num_items * transaction.discounted_price
Now every time a sale is made, a new Transaction object is created and added to the transactions list. You can view the transactions on our sample store.
store.sell(num_items=10, discount=0.1)
store.sell(num_items=3)
print(len(store.transactions)) # Output: 2