Author Dusty Phillips Reviewers



Download 2,95 Mb.
Pdf ko'rish
bet175/183
Sana20.07.2022
Hajmi2,95 Mb.
#831085
1   ...   171   172   173   174   175   176   177   178   ...   183
Bog'liq
python3-oop

[
 180 
]
Often, the need to extend a built-in data type is an indication that we're using the 
wrong sort of data type. It is not always the case, but if we are looking to extend 
a built-in, we should carefully consider whether or not a different data structure 
would be more suitable.
For example, consider what it takes to create a dictionary that remembers the order in 
which keys were inserted. One way to do this is to keep an ordered list of keys that is 
stored in a specially derived subclass of 
dict
. Then we can override the methods 
keys

values

__iter__
, and 
items
to return everything in order. Of course, we'll also have 
to override 
__setitem__
and 
setdefault
to keep our list up to date. There are likely 
to be a few other methods in the output of 
dir(dict)
that need overriding to keep the 
list and dictionary consistent (
clear
and 
__delitem__
come to mind, to track when 
items are removed), but we won't worry about them for this example.
So we'll be extending 
dict
and adding a list of ordered keys. Trivial enough, but 
where do we create the actual list? We could include it in the 
__init__
method, 
which would work just fine, but we have no guarantees that any subclass will call 
that initializer. Remember the 
__new__
method we discussed in 
Chapter 2

Objects in 
Python
? I said it was generally only useful in very special cases. This is one of those 
special cases. We know 
__new__
will be called exactly once, and we can create a list 
on the new instance that will always be available to our class. With that in mind, here 
is our entire sorted dictionary:
from collections import KeysView, ItemsView, ValuesView
class DictSorted(dict):
def __new__(*args, **kwargs):
new_dict = dict.__new__(*args, **kwargs)
new_dict.ordered_keys = []
return new_dict
def __setitem__(self, key, value):
'''self[key] = value syntax'''
if key not in self.ordered_keys:
self.ordered_keys.append(key)
super().__setitem__(key, value)
def setdefault(self, key, value):
if key not in self.ordered_keys:
self.ordered_keys.append(key)
return super().setdefault(key, value)
def keys(self):
return KeysView(self)
def values(self):
www.it-ebooks.info


Chapter 6

Download 2,95 Mb.

Do'stlaringiz bilan baham:
1   ...   171   172   173   174   175   176   177   178   ...   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