用python实现一个基于面向对象思想的、具有添加好友、删除好友、展示好友、退出功能的好友管理系统。
时间: 2023-07-10 17:05:47 浏览: 88
基于Python实现用户管理系统
好友管理系统分为用户和好友两个类,用户类包含用户的基本信息,好友类包含好友的基本信息。代码如下:
```python
class User:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
self.friends = []
def add_friend(self, friend):
self.friends.append(friend)
def remove_friend(self, friend):
if friend in self.friends:
self.friends.remove(friend)
else:
print("{} is not your friend.".format(friend.name))
def show_friends(self):
if len(self.friends) == 0:
print("You have no friends.")
else:
print("Your friends:")
for friend in self.friends:
print("- {} ({}, {})".format(friend.name, friend.age, friend.gender))
def logout(self):
print("You have logged out.")
class Friend:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
```
使用上述代码实现的好友管理系统包含添加好友、删除好友、展示好友、退出功能。示例代码如下:
```python
# 创建用户
user1 = User("Tom", 20, "male")
user2 = User("Lucy", 22, "female")
# 创建好友
friend1 = Friend("Jack", 21, "male")
friend2 = Friend("Lily", 23, "female")
# 添加好友
user1.add_friend(friend1)
user1.add_friend(friend2)
user2.add_friend(friend1)
# 展示好友
user1.show_friends()
user2.show_friends()
# 删除好友
user1.remove_friend(friend1)
user1.show_friends()
# 退出
user1.logout()
```
运行结果如下:
```
Your friends:
- Jack (21, male)
- Lily (23, female)
Your friends:
- Jack (21, male)
You have no friends.
You have logged out.
```
阅读全文