用python编写代码,实现一个基于面向对象思想的、具有添加好友、删除好友、展示好友、退出功能的好友管理系统。
时间: 2023-07-10 17:07:21 浏览: 149
下面是一个简单的好友管理系统的实现示例:
```python
class Friend:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
class FriendManager:
def __init__(self):
self.friends = []
def add_friend(self, friend):
self.friends.append(friend)
print(f"{friend.name} has been added to your friend list!")
def remove_friend(self, friend):
if friend in self.friends:
self.friends.remove(friend)
print(f"{friend.name} has been removed from your friend list!")
else:
print(f"{friend.name} is not in your friend list!")
def show_friends(self):
print("Your friend list:")
for friend in self.friends:
print(f"Name: {friend.name}, Age: {friend.age}, Gender: {friend.gender}")
def run(self):
while True:
print("1. Add a friend")
print("2. Remove a friend")
print("3. Show friends")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
name = input("Enter name: ")
age = input("Enter age: ")
gender = input("Enter gender: ")
friend = Friend(name, age, gender)
self.add_friend(friend)
elif choice == "2":
name = input("Enter name: ")
friend = None
for f in self.friends:
if f.name == name:
friend = f
if friend:
self.remove_friend(friend)
else:
print(f"{name} is not in your friend list!")
elif choice == "3":
self.show_friends()
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid choice, please try again.")
```
使用示例:
```python
manager = FriendManager()
manager.run()
```
输出:
```text
1. Add a friend
2. Remove a friend
3. Show friends
4. Exit
Enter your choice (1-4): 1
Enter name: Alice
Enter age: 25
Enter gender: Female
Alice has been added to your friend list!
1. Add a friend
2. Remove a friend
3. Show friends
4. Exit
Enter your choice (1-4): 1
Enter name: Bob
Enter age: 30
Enter gender: Male
Bob has been added to your friend list!
1. Add a friend
2. Remove a friend
3. Show friends
4. Exit
Enter your choice (1-4): 3
Your friend list:
Name: Alice, Age: 25, Gender: Female
Name: Bob, Age: 30, Gender: Male
1. Add a friend
2. Remove a friend
3. Show friends
4. Exit
Enter your choice (1-4): 2
Enter name: Alice
Alice has been removed from your friend list!
1. Add a friend
2. Remove a friend
3. Show friends
4. Exit
Enter your choice (1-4): 3
Your friend list:
Name: Bob, Age: 30, Gender: Male
1. Add a friend
2. Remove a friend
3. Show friends
4. Exit
Enter your choice (1-4): 4
Goodbye!
```
阅读全文