2017-06-20 93 views
-1

版本:python3.6.1蟒蛇OOP:扩展分类

源代码:

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","[email protected]") 
c2 = Contact("John B","[email protected]") 
c3 = Contact("Jenna C","[email protected]") 
[c.name for c in Contact.all_contacts.search('John')] 

运行的结果应该是['John A','John B'],但我的空闲秀我['John A']

我想弄清楚我的代码有什么问题吗?

+1

为什么联系人首先知道联系人列表? –

+1

不要从内置的扩展,使用ABC模块。 –

+2

'return matching_contacts'的缩进是错误的;它需要*在循环之外*。 – deceze

回答

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