Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparable classes in Python 3

Tags:

What is the standard way of making a class comparable in Python 3? (For example, by id.)

like image 632
Neil G Avatar asked Aug 02 '11 04:08

Neil G


People also ask

How do you make a class comparable in Python?

To make classes comparable, you only need to implement __lt__ and decorate the class with functools. total_ordering . You should also provide an __eq__ method if possible. This provides the rest of the comparison operators so you don't have to write any of them yourself.

Can you compare classes in Python?

When comparing two objects of a custom class using == , Python by default compares just the object references, not the data contained in the objects. To override this behavior, the class can implement the special __eq__() method, which accepts two arguments — the objects to be compared — and returns True or False .

How do you compare in Python 3?

If values of two operands are not equal, then condition becomes true. (a!= b) is true. If the value of left operand is greater than the value of right operand, then condition becomes true.

How do I use CMP in Python 3?

cmp() does not work in python 3. You might want to see list comparison in Python. Practical Application: Program to check if a number is even or odd using cmp function. Approach: Compare 0 and n%2, if it returns 0, then it is even, else its odd.


1 Answers

To make classes comparable, you only need to implement __lt__ and decorate the class with functools.total_ordering. You should also provide an __eq__ method if possible. This provides the rest of the comparison operators so you don't have to write any of them yourself.

like image 100
agf Avatar answered Oct 10 '22 03:10

agf