Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created February 20, 2026 12:40
Show Gist options
  • Select an option

  • Save sunmeat/a6f1fe4b53c672f54a5ea1aa9f3beaed to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/a6f1fe4b53c672f54a5ea1aa9f3beaed to your computer and use it in GitHub Desktop.
консольний приклад на MVT в пайтон
# Model: зберігає та маніпулює даними
class ShoppingModel:
def __init__(self):
self.items = [] # список покупок: [{'name': 'Яблука', 'quantity': 5, 'price': 77}]
def add_item(self, name, quantity, price):
self.items.append({'name': name, 'quantity': quantity, 'price': price})
def get_all_items(self):
return self.items
def calculate_total(self):
return sum(item['quantity'] * item['price'] for item in self.items)
# Template: шаблони для форматування виводу
class ShoppingTemplate:
@staticmethod
def item_template(item):
return f"{item['name']}: {item['quantity']} шт. по {item['price']} грн. (разом: {item['quantity'] * item['price']} грн.)"
@staticmethod
def list_template(items, total):
return "\n".join(ShoppingTemplate.item_template(item) for item in items) + f"\n\nЗагальна сума: {total} грн."
@staticmethod
def menu_template():
return "1. Додати товар\n2. Показати список\n3. Вихід"
# View: взаємодія з користувачем та рендеринг через шаблони
class ShoppingView:
def __init__(self, model, template):
self.model = model
self.template = template
def get_input(self, prompt):
return input(prompt)
def show_menu(self):
print(self.template.menu_template())
def add_item(self):
name = self.get_input("Назва товару: ")
quantity = int(self.get_input("Кількість: "))
price = float(self.get_input("Ціна за шт.: "))
self.model.add_item(name, quantity, price)
print("Товар додано!")
def show_list(self):
items = self.model.get_all_items()
total = self.model.calculate_total()
if items:
print(self.template.list_template(items, total))
else:
print("Список порожній.")
def run(self):
while True:
self.show_menu()
choice = self.get_input("Вибір: ")
if choice == '1':
self.add_item()
elif choice == '2':
self.show_list()
elif choice == '3':
break
else:
print("Невірний вибір.")
if __name__ == "__main__":
model = ShoppingModel()
template = ShoppingTemplate()
view = ShoppingView(model, template)
view.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment