-
-
Save stephengruppetta/cc7430de5d469c8717d726230c577ddc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Item: | |
def __init__(self, name, qty=0): | |
self.name = name | |
self.qty = qty | |
def __str__(self): | |
return f"{self.name} - {self.qty} left" | |
class VendingMachine: | |
def __init__(self): | |
self.items_on_sale = [] | |
def __getitem__(self, idx): | |
if isinstance(idx, int): | |
return self.items_on_sale[idx] | |
raise TypeError("Index should be an integer") | |
def add_items(self, items): | |
""" | |
Add items to the vending machine | |
:param items: sequence of Item objects | |
""" | |
self.items_on_sale.extend(items) | |
def buy_item(self, idx): | |
item = self[idx] | |
if item.qty > 0: | |
item.qty -= 1 | |
return item.name | |
print("This slot is empty") | |
return None # Explicitly returning None, for clarity | |
hideous_machine = VendingMachine() | |
hideous_machine.add_items( | |
[ | |
Item("Hazelnut Chocolate", 5), | |
Item("Dark Chocolate", 3), | |
Item("Still Water", 7), | |
Item("Sparkling Water", 4), | |
] | |
) | |
print(hideous_machine[2]) | |
hideous_machine.buy_item(2) | |
print(hideous_machine[2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment