Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Comparison Magic Methods | Magic Methods
In-Depth Python OOP
course content

Зміст курсу

In-Depth Python OOP

Comparison Magic Methods

Similarly to the mathematical magic methods, here we take self and other as arguments and compare their desired attributes. These magic methods should always return True or False.

Magic MethodOperation
__eq__(self, other)==
__gt__(self, other)>
__ge__(self, other)>=
__lt__(self, other)<
__le__(self, other)<=
__ne__(self, other)!=

Note

To understand the naming of these methods, look at some examples:

  • eq is equal.
  • gt is greater than.
  • le is less or equal.
  • ne is not equal.

Look at the example of Road class:

Note

To optimize the code, you can utilize existing comparison methods. For example, if you have implemented the __lt__() method (<), by implementing the __ge__() method (>=), you can use return not (instance1 < instance2) which will return the opposite result of the already implemented < operator.

Which magic method should be used?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 5. Розділ 4
We're sorry to hear that something went wrong. What happened?
some-alt