Python 实现一个类来模拟排队系统
我们将使用 Python 实现一个简单的排队系统类。这个类将允许用户添加顾客到队列中,移除顾客,以及查看当前队列的状态。
实例
class QueueSystem:
def __init__(self):
self.queue = []
def add_customer(self, name):
self.queue.append(name)
print(f"{name} has been added to the queue.")
def remove_customer(self):
if self.queue:
removed_customer = self.queue.pop(0)
print(f"{removed_customer} has been removed from the queue.")
else:
print("The queue is empty.")
def show_queue(self):
if self.queue:
print("Current queue:")
for i, customer in enumerate(self.queue, 1):
print(f"{i}. {customer}")
else:
print("The queue is empty.")
# Example usage
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} has been added to the queue.")
def remove_customer(self):
if self.queue:
removed_customer = self.queue.pop(0)
print(f"{removed_customer} has been removed from the queue.")
else:
print("The queue is empty.")
def show_queue(self):
if self.queue:
print("Current queue:")
for i, customer in enumerate(self.queue, 1):
print(f"{i}. {customer}")
else:
print("The queue is empty.")
# Example usage
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
点我分享笔记