Author Dusty Phillips Reviewers


all_contacts = ContactList()



Download 2,95 Mb.
Pdf ko'rish
bet69/183
Sana20.07.2022
Hajmi2,95 Mb.
#831085
1   ...   65   66   67   68   69   70   71   72   ...   183
Bog'liq
python3-oop

all_contacts = ContactList()
def __init__(self, name, email):
self.name = name
self.email = email
self.all_contacts.append(self)
Instead of instantiating a normal list as our class variable, we create a new 
ContactList
class that extends the built-in 
list
. Then, we instantiate this subclass 
as our 
all_contacts
list. We can test the new search functionality as follows:
>>> c1 = Contact("John A", "johna@example.net")
>>> c2 = Contact("John B", "johnb@example.net")
>>> c3 = Contact("Jenna C", "jennac@example.net")
>>> [c.name for c in Contact.all_contacts.search('John')]
['John A', 'John B']
Are you wondering how we changed the built-in syntax 
[]
into something we can 
inherit from? Creating an empty list with 
[]
is actually a shorthand for creating an 
empty list using 
list()
; the two syntaxes behave identically:
>>> [] == list()
True
www.it-ebooks.info


Chapter 3
[
 63 
]
In reality, the 
[]
syntax is actually so-called 
syntax sugar
that calls the 
list()
constructor under the hood. The 
list
data type is a class that we can extend.
In fact, the list itself extends the 
object
class:
>>> isinstance([], object)
True
As a second example, we can extend the 
dict
class, which is, similar to the list, the 
class that is constructed when using the 
{}
syntax shorthand:
class LongNameDict(dict):
def longest_key(self):
longest = None
for key in self:
if not longest or len(key) > len(longest):
longest = key
return longest
This is easy to test in the interactive interpreter:

Download 2,95 Mb.

Do'stlaringiz bilan baham:
1   ...   65   66   67   68   69   70   71   72   ...   183




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish