Implement a simple online chat room class using Python

Document 对象参考手册Python3 Examples

We will use Python to implement a simple online chat room class. This chat room class will allow users to join the chat room, send messages, and view chat history. We will use a list to store the chat history and use 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", "Hello Alice!")
chat_room.leave("Alice")
chat_room.show_messages()

Code analysis:

  1. __init__Method: Initialize the chat room, set the chat room name, and create empty user list and message list.
  2. joinMethod: Allow users to join the chat room and add the join message to the message list.
  3. leaveMethod: Allow users to leave the chat room and add the leave message to the message list.
  4. send_messageMethod: Allow users to send messages and add the message to the message list.
  5. show_messagesMethod: Display all chat history.

Output:

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

Document 对象参考手册Python3 Examples

Other extensions