Handling Transactions
If we want to process transactions, we need to introduce money to our Store. Let's add a balance attribute to keep track of how much money we've got in the store and a price attribute to represent the price of the product.
class Store:
def __init__(name: str, inventory: int, balance: float price: float) -> None:
self.name = name
self.inventory = inventory
self.balance
store = Store(
name="Awesome Store",
inventory=100,
balance=0.0,
price=10.0
)
To handle our first transaction, we can subtract from inventory again, but this time we also need to add to balance the price of the product sold.
num_items = 10
total_cost = num_items * store.price
store.inventory -= num_items
store.balance += total_cost
How about if we wanted to offer a discount?
discount = 0.1 # 10% discount
price = store.price * (1 - discount)
total_cost = number_items * price
store.inveventory -= number_items
store.balance += total_cost
Great! But you can see this is getting a bit messy, having to write the same code over and over again each time we make a transaction. Let's refactor this into a method called sell that takes the number of items and an optional discount.
class Store:
...
def sell(self, num_items: int, discount: float = 0.0) -> None:
price = self.price * (1 - discount)
total_cost = num_items * price
self.inventory -= num_items
self.balance += total_cost
One small issue here: What if we don't have enough inventory to sell the requested number of items? Let's add a check to handle this case. If there isn't enough inventory, we can raise an exception.
class Store:
...
def sell(self, num_items: int, discount: float = 0.0) -> None:
if num_items > self.inventory:
raise ValueError("Not enough inventory to complete the sale.")
price = self.price * (1 - discount)
total_cost = num_items * price
self.inventory -= num_items
self.balance += total_cost