Author Dusty Phillips Reviewers



Download 2,95 Mb.
Pdf ko'rish
bet165/183
Sana20.07.2022
Hajmi2,95 Mb.
#831085
1   ...   161   162   163   164   165   166   167   168   ...   183
Bog'liq
python3-oop

[
 170 
]
If we want to place objects we define ourselves into a list and make those objects 
sortable, we have to do a bit more work. The special method 
__lt__
, which stands for 
"less than", should be defined on the class to make instances of that class comparable. 
The 
sort
method on list will access this method on each object to determine where it 
goes in the list. This method should return 
True
if our class is somehow less than the 
passed parameter, and 
False
otherwise. Here's a rather silly class that can be sorted 
based on either a string or a number:
class WeirdSortee:
def __init__(self, string, number, sort_num):
self.string = string
self.number = number
self.sort_num = sort_num
def __lt__(self, object):
if self.sort_num:
return self.number < object.number
return self.string < object.string
def __repr__(self):
return"{}:{}".format(self.string, self.number)
The 
__repr__
method makes it easy to see the two values when we print a list. 
The 
__lt__
method's implementation compares the object to another instance of 
the same class (or any duck typed object that has 
string

number
, and 
sort_num
attributes; it will fail if those attributes are missing). The following output illustrates 
this class in action, when it comes to sorting:
>>> a = WeirdSortee('a', 4, True)
>>> b = WeirdSortee('b', 3, True)
>>> c = WeirdSortee('c', 2, True)
>>> d = WeirdSortee('d', 1, True)
>>> l = [a,b,c,d]
>>> l
[a:4, b:3, c:2, d:1]
>>> l.sort()
>>> l
[d:1, c:2, b:3, a:4]
www.it-ebooks.info


Chapter 6

Download 2,95 Mb.

Do'stlaringiz bilan baham:
1   ...   161   162   163   164   165   166   167   168   ...   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