Python implementation of a class to simulate a queuing system

Document 对象参考手册Python3 Examples

We will use Python to implement a simple queuing system class. This class will allow users to add customers to the queue, remove customers, and view the current queue status.

Example

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()

Code analysis:

  1. QueueSystemWhen the class is initialized, an empty list is createdqueueto store customers.
  2. add_customerThe method accepts a customer's name and adds it to the end of the queue.
  3. remove_customerThe method removes the first customer in the queue (i.e., the customer who joined earliest). If the queue is empty, it prompts that the queue is empty.
  4. show_queueThe method displays all customers in the current queue. If the queue is empty, it prompts that the queue is empty.

Output result:

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

Document 对象参考手册Python3 Examples

Other extensions