python - What does append(self) mean in Python classes?
问题描述
I am new to OOP in Python and working on inheritance concept. I came across the following code:
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)
I'm wondering why do we use self.all_contacts.append(self)
and how does for contact in self
work ?. If I understood correctly, self
appoints to the instance of a class (object), and appending to a list is not trivial to me.
解决方案
all_contacts
is a class variable -- it is unique to the class, not to each instance. It can be accessed with Contact.all_contacts
. Whenever you create a new contact, it is appended to this list of all contacts.
ContactList
inherits from list
, so for contact in self
works the same way as for i in [1,2,3]
-- it will loop through all the items that it contains. The only thing that it does differently from a list
is implement a new method, search
.
推荐阅读
- javascript - 从 setTimeout() 调用 setInterval() 不会启动计时器
- c - 指向数组的指针与指向“const”数组的指针不兼容?
- google-apps-script - 获取单元格的当前值与其在谷歌表格中的先前值之间的差异
- javascript - 带有“数组中的项目”的Javascript for循环不适用于DOM元素?
- javascript - 本地html加载txt文件
- r - 如何将 for 循环内的基本 R Plot 更改为 ggplot?
- reactjs - React 本机 flatlist 倒序
- parsing - 使用 attoparsec 在 Haskell 中重载字符串的问题
- python - 网络浏览器打开位置python
- ios - 验证 MYAPP.app 的代码签名失败