版本: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:
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)
然后在IDLE
中运行它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']
我想知道我的代码有什么问题吗?
答案 0 :(得分:0)
嗯,那是因为你的“回归”处于错误的位置。
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