Python Implement a Class to Simulate a Queuing System
We will implement a simple queuing system class in Python. It lets users add customers to the queue, remove customers, and view the current state of the queue.
Example
class
QueueSystem:
def
init
(
self
)
:
self
.
queue
=
[
]
def
add_customer
(
self
,
name
)
:
self
.
queue
.
append
(
name
)
(
f
"{name} has been added to the queue."
)
def
remove_customer
(
self
)
:
if
self
.
queue
:
removed_customer
=
self
.
queue
.
pop
(
0
)
(
f
"{removed_customer} has been removed from the queue."
)
else
:
(
"The queue is empty."
)
def
show_queue
(
self
)
:
if
self
.
queue
:
(
"Current queue:"
)
for
i
,
customer
in
enumerate
(
self
.
queue
,
1
)
:
(
f
"{i}. {customer}"
)
else
:
(
"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:
QueueSystemThe class initializer creates an empty listqueueto store the customers.add_customerThe method takes a customer's name and adds it to the end of the queue.remove_customerThe method removes the first customer in the queue (the one who joined earliest); if the queue is empty it reports that the queue is empty.show_queueThe method displays all customers currently in the queue; if the queue is empty it reports 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
Python3 Examples