python编程一个面向对象思想的、具有添加好友、删除好友、展示好友、退出功能的好友管理系统
时间: 2023-07-10 08:05:48 浏览: 103
面向对象的小项目[好友管理]
好的,下面是一个简单的面向对象思想的好友管理系统的代码示例:
```python
class Friend:
def __init__(self, name, phone_number):
self.name = name
self.phone_number = phone_number
def __str__(self):
return f"{self.name} ({self.phone_number})"
class FriendManager:
def __init__(self):
self.friends = []
def add_friend(self, name, phone_number):
friend = Friend(name, phone_number)
self.friends.append(friend)
print(f"{name} has been added as a friend.")
def remove_friend(self, name):
for friend in self.friends:
if friend.name == name:
self.friends.remove(friend)
print(f"{name} has been removed from friends.")
return
print(f"{name} is not in your friends list.")
def show_friends(self):
if len(self.friends) == 0:
print("You have no friends.")
else:
print("Your friends:")
for friend in self.friends:
print(friend)
def quit(self):
print("Goodbye!")
exit()
if __name__ == "__main__":
friend_manager = FriendManager()
while True:
print("\nWhat would you like to do?")
print("1. Add a friend")
print("2. Remove a friend")
print("3. Show friends")
print("4. Quit")
choice = input("Enter a number: ")
if choice == "1":
name = input("Enter the friend's name: ")
phone_number = input("Enter the friend's phone number: ")
friend_manager.add_friend(name, phone_number)
elif choice == "2":
name = input("Enter the friend's name: ")
friend_manager.remove_friend(name)
elif choice == "3":
friend_manager.show_friends()
elif choice == "4":
friend_manager.quit()
else:
print("Invalid choice. Please enter a number from 1-4.")
```
这个程序定义了两个类:`Friend` 和 `FriendManager`。`Friend` 类表示一个好友,有名字和电话号码属性,还有一个重载的 `__str__` 方法用于打印好友信息。`FriendManager` 类是管理好友的主要类,有添加、删除、展示和退出功能。
在主程序中,我们创建了一个 `FriendManager` 实例,并进入一个循环,让用户选择要进行的操作。根据用户的选择,调用 `FriendManager` 对应的方法来执行相应的操作。
阅读全文