下面是一個簡單的通訊錄管理系統的Python實現:
class Contact:
def __init__(self, name, phone):
self.name = name
self.phone = phone
class ContactBook:
def __init__(self):
self.contacts = []
def add_contact(self, name, phone):
contact = Contact(name, phone)
self.contacts.append(contact)
print("Contact added successfully.")
def delete_contact(self, name):
for contact in self.contacts:
if contact.name == name:
self.contacts.remove(contact)
print("Contact deleted successfully.")
return
print("Contact not found.")
def search_contact(self, name):
for contact in self.contacts:
if contact.name == name:
print("Contact found - Name: {}, Phone: {}".format(contact.name, contact.phone))
return
print("Contact not found.")
def display_contacts(self):
if len(self.contacts) == 0:
print("No contacts found.")
else:
print("Contacts:")
for contact in self.contacts:
print("Name: {}, Phone: {}".format(contact.name, contact.phone))
def menu():
print("1. Add Contact")
print("2. Delete Contact")
print("3. Search Contact")
print("4. Display Contacts")
print("5. Quit")
contact_book = ContactBook()
while True:
menu()
choice = int(input("Enter your choice: "))
if choice == 1:
name = input("Enter name: ")
phone = input("Enter phone number: ")
contact_book.add_contact(name, phone)
elif choice == 2:
name = input("Enter name: ")
contact_book.delete_contact(name)
elif choice == 3:
name = input("Enter name: ")
contact_book.search_contact(name)
elif choice == 4:
contact_book.display_contacts()
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")
該程序使用了兩個類:Contact
表示一個聯系人,ContactBook
表示通訊錄。ContactBook
類包含了添加聯系人、刪除聯系人、搜索聯系人和顯示聯系人等方法。主程序循環顯示菜單,根據用戶選擇執行相應的操作。