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

Implementing a Simple Online Chat Room Class in Python

Implementing a Simple Online Chat Room Class in Python

Document Object Reference Manual Python3 Examples

We will implement a simple online chat room class in Python. The chat room allows users to join, send messages and view the chat history. We will use a list to store the chat history and class methods to manage users and messages.

Example

class

ChatRoom:

   

def

init

(

self

,

name

)

:

       

self

.

name

=

name

       

self

.

users

=

[

]

       

self

.

messages

=

[

]

   

def

join

(

self

,

user

)

:

       

self

.

users

.

append

(

user

)

       

self

.

messages

.

append

(

f

"{user} joined the chat room."

)

   

def

leave

(

self

,

user

)

:

       

self

.

users

.

remove

(

user

)

       

self

.

messages

.

append

(

f

"{user} left the chat room."

)

   

def

send_message

(

self

,

user

,

message

)

:

       

self

.

messages

.

append

(

f

"{user}: {message}"

)

   

def

show_messages

(

self

)

:

       

for

message

in

self

.

messages

:

           

print

(

message

)

Example usage

chat_room

=

ChatRoom

(

"Python Chat Room"

)

chat_room.

join

(

"Alice"

)

chat_room.

join

(

"Bob"

)

chat_room.

send_message

(

"Alice"

,

"Hello everyone!"

)

chat_room.

send_message

(

"Bob"

,

"Hi Alice!"

)

chat_room.

leave

(

"Alice"

)

chat_room.

show_messages

(

)

Code analysis:

  1. __init__ method: initializes the chat room, sets the room name, and creates empty user and message lists.
  2. join method: lets a user join the chat room and appends a join message to the message list.
  3. leave method: lets a user leave the chat room and appends a leave message to the message list.
  4. send_message method: lets a user send a message and appends it to the message list.
  5. show_messages method: displays the whole chat history.

Output result:

Alice 加入了聊天室。
Bob 加入了聊天室。
Alice: 大家好!
Bob: 你好 Alice!
Alice 离开了聊天室。

Document Object Reference Manual Python3 Examples