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

bookComparison 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.
12345
a = 12.3 b = 5.7 print("a >= b is", a >= b) print("a.__ge__(b) is", a.__ge__(b))
copy

Look at the example of Road class:

123456789101112131415161718
class Road: def __init__(self, length): self.length = length def __eq__(self, other): if isinstance(other, Road): return self.length == other.length # compare with road return self.length == other # compare with number road_1 = Road(20) road_2 = Road(30) road_3 = Road(20) print(road_1 == road_2) print(road_1 == road_3) print(road_1 == 20) print(road_1 == 20.0) print(road_1 == 1412)
copy

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.

question mark

Which magic method should be used?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 5.  4
some-alt