Python 基于列表实现的通讯录管理系统
# 通讯录管理系统
class Contact:
def __init__(self, name, phone):
self.name = name
self.phone = phone
class ContactsList:
def __init__(self):
self.contact_list = []
def add_contact(self, name, phone):
self.contact_list.append(Contact(name, phone))
def show_contacts(self):
for contact in self.contact_list:
print(f"Name: {contact.name}, Phone: {contact.phone}")
def search_contact(self, name):
for contact in self.contact_list:
if contact.name == name:
print(f"Name: {contact.name}, Phone: {contact.phone}")
return
print("Contact not found.")
def delete_contact(self, name):
self.contact_list = [contact for contact in self.contact_list if contact.name != name]
def update_contact(self, name, new_phone):
for contact in self.contact_list:
if contact.name == name:
contact.phone = new_phone
print("Contact updated successfully.")
return
print("Contact not found.")
# 使用示例
contacts = ContactsList()
contacts.add_contact("Alice", "12345")
contacts.add_contact("Bob", "67890")
contacts.show_contacts()
contacts.search_contact("Alice")
contacts.delete_contact("Alice")
contacts.update_contact("Bob", "54321")
contacts.show_contacts()
这段代码定义了Contact
和ContactsList
两个类,分别用于表示单个联系人和通讯录列表。通过添加、显示、搜索、删除和更新联系人的方法,实现了一个简单的通讯录管理系统。
评论已关闭