Реализация класса на Python для имитации системы очередей
Мы будем использовать Python для реализации простого класса системы очередей. Этот класс позволит пользователям добавлять клиентов в очередь, удалять клиентов и просматривать текущее состояние очереди.
Пример
class QueueSystem:
def __init__(self):
self.queue = []
def add_customer(self, name):
self.queue.append(name)
print(f"{name} добавлен в очередь.")
def remove_customer(self):
if self.queue:
removed_customer = self.queue.pop(0)
print(f"{removed_customer} удален из очереди.")
else:
print("Очередь пуста.")
def show_queue(self):
if self.queue:
print("Текущая очередь:")
for i, customer in enumerate(self.queue, 1):
print(f"{i}. {customer}")
else:
print("Очередь пуста.")
# Пример использования
queue_system = QueueSystem()
queue_system.add_customer("Alice")
queue_system.add_customer("Bob")
queue_system.show_queue()
queue_system.remove_customer()
queue_system.show_queue()
def __init__(self):
self.queue = []
def add_customer(self, name):
self.queue.append(name)
print(f"{name} добавлен в очередь.")
def remove_customer(self):
if self.queue:
removed_customer = self.queue.pop(0)
print(f"{removed_customer} удален из очереди.")
else:
print("Очередь пуста.")
def show_queue(self):
if self.queue:
print("Текущая очередь:")
for i, customer in enumerate(self.queue, 1):
print(f"{i}. {customer}")
else:
print("Очередь пуста.")
# Пример использования
queue_system = QueueSystem()
queue_system.add_customer("Alice")
queue_system.add_customer("Bob")
queue_system.show_queue()
queue_system.remove_customer()
queue_system.show_queue()
Анализ кода:
QueueSystemПри инициализации класса создаётся пустой списокqueueдля хранения клиентов.add_customerМетод принимает имя клиента и добавляет его в конец очереди.remove_customerМетод удаляет первого клиента в очереди (т. е. клиента, который встал в очередь раньше всех). Если очередь пуста, выводится сообщение, что очередь пуста.show_queueМетод отображает всех клиентов в текущей очереди. Если очередь пуста, выводится сообщение, что очередь пуста.
Результат вывода:
Alice has been added to the queue. Bob has been added to the queue. Current queue: 1. Alice 2. Bob Alice has been removed from the queue. Current queue: 1. BobДругие расширения
Python3 Примеры