pythonoop:扩展类
版本:python3.6.1 源代码:pythonoop:扩展类,python,Python,版本:python3.6.1 源代码: class ContactList(list): def search(self,name): '''Return all contacts that contain the search value in their name.''' matching_contacts = [] for contact in self: if name in contact.name:
class ContactList(list):
def search(self,name):
'''Return all contacts that contain the search value in their name.'''
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacts = ContactList()
def __init__(self,name,email):
self.name = name
self.email = email
Contact.all_contacts.append(self)
然后空转
c1 = Contact("John A","johna@example.com")
c2 = Contact("John B","johnb@example.com")
c3 = Contact("Jenna C","jennac@example.com")
[c.name for c in Contact.all_contacts.search('John')]
结果应该是['John A','John B']
,但我的空闲显示为['John A']
我想知道我的代码出了什么问题 那是因为你的“返回”位置不对
class ContactList(list):
def search(self,name):
'''Return all contacts that contain the search value in their name.'''
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
为什么联系人首先会知道联系人列表?不要从内置扩展,使用ABC模块。
返回匹配的联系人的缩进是错误的;它需要在循环之外。并且您正在大量混合实例和类成员…found=[如果item中的“John”,则所有_联系人中的item对应item]