Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Class to Simulate a Queuing System

Python Implement a Class to Simulate a Queuing System

Document Object Reference Manual Python3 Examples

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

)

       

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. QueueSystem The class initializer creates an empty list queue to store the customers.
  2. add_customer The method takes a customer's name and adds it to the end of the queue.
  3. remove_customer The 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.
  4. show_queue The 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

Document Object Reference Manual Python3 Examples