-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']
我想弄清楚我的代碼有什麼問題嗎?
爲什麼聯繫人首先知道聯繫人列表? –
不要從內置的擴展,使用ABC模塊。 –
'return matching_contacts'的縮進是錯誤的;它需要*在循環之外*。 – deceze