代码:
# 定义联系人类 class Contact: def __init__(self, name, phone, street, city, province, postcode): self.name = name self.phone = phone self.street = street self.city = city self.province = province self.postcode = postcode def __str__(self): return f"姓名:{self.name};电话:{self.phone};地址:{self.province} {self.city} {self.street},{self.postcode}" # 定义通讯录类 class AddressBook: def __init__(self): self.contacts = [] # 添加联系人 def add_contact(self, contact): self.contacts.append(contact) print(f"{contact.name}已添加到通讯录。") # 显示所有联系人 def show_contacts(self): print("所有联系人:") for contact in self.contacts: print(contact) # 查找联系人 def find_contact(self, name): for contact in self.contacts: if contact.name == name: print(contact) return print(f"未找到姓名为{name}的联系人。") # 修改联系人 def edit_contact(self, name): for contact in self.contacts: if contact.name == name: print(f"原信息:{contact}") new_name = input("请输入新姓名:") new_phone = input("请输入新电话:") new_street = input("请输入新街道:") new_city = input("请输入新城市:") new_province = input("请输入新省份:") new_postcode = input("请输入新邮编:") contact.name = new_name contact.phone = new_phone contact.street = new_street contact.city = new_city contact.province = new_province contact.postcode = new_postcode print(f"{name}的信息已更新为{contact}.") return print(f"未找到姓名为{name}的联系人。") # 删除联系人 def del_contact(self, name): for contact in self.contacts: if contact.name == name: self.contacts.remove(contact) print(f"{name}已从通讯录中删除。") return print(f"未找到姓名为{name}的联系人。") # 主程序 if __name__ == '__main__': address_book = AddressBook() while True: print("请选择操作:") print("1. 添加联系人") print("2. 显示所有联系人") print("3. 查找联系人") print("4. 修改联系人") print("5. 删除联系人") print("0. 退出程序") choice = input() if choice == "1": name = input("请输入姓名:") phone = input("请输入电话:") street = input("请输入街道:") city = input("请输入城市:") province = input("请输入省份:") postcode = input("请输入邮编:") contact = Contact(name, phone, street, city, province, postcode) address_book.add_contact(contact) elif choice == "2": address_book.show_contacts() elif choice == "3": name = input("请输入要查找的姓名:") address_book.find_contact(name) elif choice == "4": name = input("请输入要修改的姓名:") address_book.edit_contact(name) elif choice == "5": name = input("请输入要删除的姓名:") address_book.del_contact(name) elif choice == "0": print("程序已退出。") break else: print("无效的选择,请重新输入。")结果图;