Making Classes Sortable & Comparable In Python

preview_player
Показать описание
In this tutorial we will be learning how we can make our Python classes both sortable AND comparable. This can be very useful if there are specific parts of your classes that you'd like to use for sorting and comparing.

▶ Become job-ready with Python:

▶ Follow me on Instagram:

00:00 Intro
00:19 The Issue
00:34 Starting With The Code
02:05 Using: __lt__ in Python
02:51 Solved?
03:23 Other Benefits
04:02 Using: __gt__ in Python
04:49 Using: __eq__ in Python
05:52 That’s All For Today!
Рекомендации по теме
Комментарии
Автор

One other handy trick is to utilise the functools module's `total_ordering` decorator. Once you supply the eq dunder, as well as either an lt, le, gt, or ge, that decorator will populate the class with everything else. It does come with one or two caveats though, so worth checking the docs to make sure it's right for you before using it.

Carberra
Автор

Cool practical explanation. More dunder and OOP 👌

chris-spartan
Автор

While I do love dunder methods in Python, for something like this I feel that a dataclass might be a better fit as it saves you the trouble of having to write a bunch of dunder methods and removes the potential for little annoying errors that can be hard to track down. And if the default method isn't up to you're standards, you can always write your own implementation using the methods shown in this video.

bipolarchemist
Автор

Might be a little advanced for the kind of content you like to make, but defining custom import behavior through importlib and the meta path might be interesting.

celestialowl
Автор

Thanks for the refresh! Happy new year brother :)

idobooks
Автор

I think it was a retrograde step removing three-way comparison in Python 3. __cmp__ was analogous to the spaceship operator in Ruby and C++20.

davidgillies
Автор

bro if i want like this pepole.sort(key= "name") like specifying custom sorting if key value is name then sort by name else sort by age. todo it what are the changes we do in Person class implementation?

coderunner
Автор

Don't we need to implement <= (less than or equal)? In Python this should be __le__. Does your code actually work when two persons have the same age?

ScriptRaccoon
Автор

Also egal welches Video du hier ablieferst bei mir hat noch kein Code von dir bei mir funktioniert nicht einer ...

raelephesantas
join shbcf.ru