Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.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
在Python类中,append(self)是什么意思?_Python_Class_Object_Self - Fatal编程技术网

在Python类中,append(self)是什么意思?

在Python类中,append(self)是什么意思?,python,class,object,self,Python,Class,Object,Self,我是Python中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

我是Python中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
        self.all_contacts.append(self)

我想知道为什么我们要使用
self.all\u contacts.append(self)
,self中的联系人
是如何工作的?。如果我理解正确,
self
指定类(对象)的实例,并将其附加到列表中对我来说并不简单。

所有联系人
都是一个类变量——它是类的唯一变量,而不是每个实例的唯一变量。可通过
联系人访问。所有联系人
。无论何时创建新联系人,都会将其附加到此所有联系人列表中


联系人列表
继承自
列表
,因此
对于自身联系人
的工作方式与[1,2,3]中的i的
相同
——它将循环遍历它包含的所有项目。它与
列表
唯一不同的地方是实现了一种新方法,
搜索

好吧,基本上你创建了一个
联系人
列表,并添加
self
所有联系人
列表中添加当前联系人

现在回答你们的问题

我想知道为什么我们要使用self.all_contacts.append(self)

我们会使用它,因为
all_contacts
是一个类变量,这意味着该列表将在所有
Contact
实例之间共享

自我接触的
是如何工作的

正如您所说,由于
self
表示当前实例,因此在self
中调用
for contact允许您在当前联系人列表上进行迭代


换句话说,代码示例允许您创建
Contact
实例,该实例将自动附加到类变量(共享)中。现在,通过提供继承自
列表
联系人列表
类,它们允许您使用实现的
搜索
方法,该方法将根据您的搜索筛选器返回另一个
联系人
列表。

所有联系人
都是
联系人
的类变量,初始化为
联系人列表
的一个实例,是
列表
的一个子类,因此当通过
\uuuu init\uuuuu
方法实例化一个新的
联系人
实例时,
self
被分配给正在实例化的新实例和
self.all\u contacts.append(self)
会将新的
联系人
实例添加到
所有联系人
列表中。这样,
Contact.all_contacts
将维护已实例化的所有
Contact
实例的列表