python简易通讯录
时间: 2024-04-10 17:26:10 浏览: 85
Python简易通讯录是一个基于Python语言开发的简单联系人管理系统,它可以帮助用户存储和管理联系人的信息。以下是一个简单的Python通讯录的实现示例:
```python
class Contact:
def __init__(self, name, phone_number):
self.name = name
self.phone_number = phone_number
class AddressBook:
def __init__(self):
self.contacts = []
def add_contact(self, contact):
self.contacts.append(contact)
def search_contact(self, name):
for contact in self.contacts:
if contact.name == name:
return contact
return None
def delete_contact(self, name):
contact = self.search_contact(name)
if contact:
self.contacts.remove(contact)
print(f"成功删除联系人:{name}")
else:
print(f"未找到联系人:{name}")
def display_contacts(self):
if len(self.contacts) == 0:
print("通讯录为空")
else:
print("通讯录中的联系人:")
for contact in self.contacts:
print(f"姓名:{contact.name},电话:{contact.phone_number}")
# 创建通讯录对象
address_book = AddressBook()
# 添加联系人
contact1 = Contact("张三", "123456789")
address_book.add_contact(contact1)
contact2 = Contact("李四", "987654321")
address_book.add_contact(contact2)
# 显示所有联系人
address_book.display_contacts()
# 搜索联系人
search_name = "张三"
result = address_book.search_contact(search_name)
if result:
print(f"找到联系人:{result.name},电话:{result.phone_number}")
else:
print(f"未找到联系人:{search_name}")
# 删除联系人
delete_name = "李四"
address_book.delete_contact(delete_name)
# 再次显示所有联系人
address_book.display_contacts()
```
阅读全文