2017-06-20 27 views
-1

:python3.6.1Pythonの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) 

、結果は['John A','John B']する必要がありますが、私のアイドルは私を見る

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']

私のコードで何が間違っているのか把握したいのですか?

+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