面向对象的方法编程通讯录
时间: 2024-01-19 22:04:13 浏览: 177
实现一个基于面向对象的通讯录,可以包括以下类:
1. Person类:包括姓名、电话、地址等信息,可以设置和获取这些信息。
2. Contact类:包括一个Person对象和一个备注字符串,可以设置和获取这些信息。
3. AddressBook类:包括一个Contact对象列表,可以添加、删除、查找和显示联系人信息。
下面是一个示例代码:
```
class Person:
def __init__(self, name, phone, address):
self.name = name
self.phone = phone
self.address = address
def set_name(self, name):
self.name = name
def set_phone(self, phone):
self.phone = phone
def set_address(self, address):
self.address = address
def get_name(self):
return self.name
def get_phone(self):
return self.phone
def get_address(self):
return self.address
class Contact:
def __init__(self, person, note):
self.person = person
self.note = note
def set_person(self, person):
self.person = person
def set_note(self, note):
self.note = note
def get_person(self):
return self.person
def get_note(self):
return self.note
class AddressBook:
def __init__(self):
self.contacts = []
def add_contact(self, contact):
self.contacts.append(contact)
def remove_contact(self, contact):
self.contacts.remove(contact)
def find_contact(self, name):
results = []
for contact in self.contacts:
if contact.get_person().get_name() == name:
results.append(contact)
return results
def display_contacts(self):
for contact in self.contacts:
person = contact.get_person()
print("Name: {}\nPhone: {}\nAddress: {}\nNote: {}\n".format(person.get_name(), person.get_phone(), person.get_address(), contact.get_note()))
# 创建一个通讯录对象
address_book = AddressBook()
# 创建两个联系人
person1 = Person("John", "1234567890", "123 Main St")
person2 = Person("Jane", "0987654321", "456 Oak Ave")
# 创建两个联系对象并添加到通讯录中
contact1 = Contact(person1, "Friend")
address_book.add_contact(contact1)
contact2 = Contact(person2, "Colleague")
address_book.add_contact(contact2)
# 显示通讯录中的联系人
address_book.display_contacts()
# 查找联系人并显示结果
results = address_book.find_contact("John")
for contact in results:
print(contact.get_person().get_name())
阅读全文