Implementing a Simple Online Chat Room Class in Python
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
:
(
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:
__init__method: initializes the chat room, sets the room name, and creates empty user and message lists.joinmethod: lets a user join the chat room and appends a join message to the message list.leavemethod: lets a user leave the chat room and appends a leave message to the message list.send_messagemethod: lets a user send a message and appends it to the message list.show_messagesmethod: displays the whole chat history.
Output result:
Alice 加入了聊天室。
Bob 加入了聊天室。
Alice: 大家好!
Bob: 你好 Alice!
Alice 离开了聊天室。
Python3 Examples