python实现好友管理系统的基本功能,包括添加好友、删除好友、备注好友、展示好友等。
时间: 2024-11-16 15:20:48 浏览: 5
好友管理python课程设计.7z
5星 · 资源好评率100%
在Python中实现一个基础的好友管理系统,我们可以设计一个简单的类结构,比如`User`和`FriendManager`。这里是一个基本的设计:
```python
class User:
def __init__(self, id, name, nickname=None):
self.id = id
self.name = name
self.nickname = nickname
self.friends = []
def add_friend(self, friend_id):
if friend_id not in [u.id for u in self.friends]:
self.friends.append(friend_id)
def delete_friend(self, friend_id):
if friend_id in [u.id for u in self.friends]:
self.friends.remove(friend_id)
def set_nickname(self, friend_id, nickname):
for user in self.friends:
if user == friend_id:
user.nickname = nickname
def show_friends(self):
return {f'id': u.id, 'name': u.name, 'nickname': u.nickname} for u in self.friends
class FriendManager:
def __init__(self):
self.users = {}
def add_user(self, user):
self.users[user.id] = user
def remove_user(self, user_id):
if user_id in self.users:
del self.users[user_id]
def manage_friend(self, user_id, action, *args):
if user_id in self.users:
getattr(self.users[user_id], action)(*args)
# 使用示例
manager = FriendManager()
user1 = User(1, 'Alice')
user2 = User(2, 'Bob', 'Bobo')
manager.add_user(user1)
manager.add_user(user2)
user1.add_friend(user2.id) # 添加好友
user1.set_nickname(user2.id, 'Bobby') # 贝记好友昵称
manager.manage_friend(user1.id, 'show_friends') # 展示好友列表
阅读全文