python - Inheritance of built in types. Where did the author obtain the 'self' in the for loop -
class contactlist(list): def search(self, name): matching_contacts = [] 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) print([c.name c in contact.all_contacts.search('john')]) >>> ['john a']
this class author wrote. creates class inherits built in type list. have trouble understanding loop. since author uses loop i.e 'for contact in self' resulting in me thinking self =[] declared somewhere. author not explicitly write leads me assume in parent class there def init method provides self = []. unsure if understanding correct or there else entirely not seeing.
also not understand author obtain contact.name in if statement.
edit
i have added full code. search result produces 'john a' , should include 'john b' have no idea why not working.
self
refers actual instance of contactlist
. since contactlist
subclass of list
, list
, self
can iterated on in loop can list
.
you can see list methods using help(list)
whilst in interpreter, or reading python documentation or tutorial.
where did contact.name
come from? in search()
method each element of contactlist
(accessed via self
) bound in turn contact
loop, , element contains attribute named name
. example simple class contact
:
class contact(object): def __init__(self, name, phone=none): self.name = name self.phone = phone >>> contacts = contactlist([contact('me','555-1234'), contact('you','555-4321'), contact('someone else')]) >>> contacts.search('you') [<__main__.contact object @ 0x7f258eab0fd0>] >>> contacts.search('nobody') [] >>> contacts.search('e') [<__main__.contact object @ 0x7f258eab0f50>, <__main__.contact object @ 0x7f258eabe050>] # 'me' , "someone else'
note there bug in search()
method (or maybe it's error introduced when posting code here?)
return matching_contacts
is within body of loop , executed on first iteration of loop. means search check first element of contact list. return statement should deindented same level loop this:
class contactlist(list): def search(self, name): matching_contacts = [] contact in self: if name in contact.name: matching_contacts.append(contact) return matching_contacts
Comments
Post a Comment