Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
pythonoop:扩展类_Python - Fatal编程技术网

pythonoop:扩展类

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:

版本: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)
然后空转

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]