HOWTO · Python
Python の__eq__メソッド
このチュートリアルでは、Python で__eq__メソッドについて学ぶ方法を示します
このページの内容
このガイドでは、Python で __eq__() メソッドを処理する方法を説明します。さまざまなオブジェクトを作成し、この特定のメソッドの機能を学習します。それに飛び込みましょう。
Python の __eq__()
まず、__eq__() はダンダー/マジックメソッドです。これは、前後に 2つのアンダースコアが付いていることがわかります。== 演算子を使用するときはいつでも、このメソッドは 2つのクラスインスタンスを比較するためにすでに呼び出されています。__eq__() メソッドの特定の実装を提供しない場合、Python は比較のために is 演算子を使用します。しかし、この方法をどのように指定しますか?その答えは、この関数をオーバーライドすることにあります。次のコードを見てください。
# __eq__ this is called dunder/magic method in python
# class of student has constructor with two arguments
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
# object one of class student
s1 = Student("David", 293)
# object two of class student
s2 = Student("David", 293)
# Applying equality function two objects
print(s1 == s2)
出力:
False
ご覧のとおり、Student という名前のクラスを作成し、その引数の 2つを name と roll として作成しました。後で、同じ Student クラスデータを特徴とする 2つのインスタンスを作成しました。上記のコードで行ったようにこれら 2つのインスタンスを比較すると、false の出力が得られます。
これらのインスタンスは同じデータを持っていますが、一度比較すると等しくありません。これは、== 演算子がケースのアドレスを比較するためですが、これは異なります。次のコードと上記のコードを実行すると、それを確認できます。
# Both objects have different ids thats why the s1==s2 is false
print(id(s1))
print(id(s2))
出力:
1991016021344 //(it will vary)
1991021345808 //(it will vary)
ただし、インスタンスを作成し、後でそのインスタンスを次のような別の例で保存すると、それらのアドレスは同じになります。見てみましょう。
# object one of class student
s1 = Student("Ahsan", 293)
s3 = s1
# In this case we have same id for s1 and s3
print(s1 == s3)
print(id(s1))
print(id(s3))
出力:
True
1913894976432 //(it will vary)
1913894976432 //(it will vary)
それはあなたに true を出力として与えるでしょう。では、データに基づいて 2つのインスタンスをどのように比較できますか?dunder メソッドを実装し、次のようにオーバーライドする必要があります。
# class of student has constructor with two arguments and a modified dunder method of __eq__
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
# implementing the dunder method
def __eq__(self, obj):
# checking both objects of same class
if isinstance(obj, Student):
if self.roll == obj.roll:
return True
else:
return False
# object of class student
s4 = Student("David", 293)
# other object of class student
s5 = Student("David", 293)
# Applying equality function two objects
print(s4 == s5)
# Both objects have different ids, but the s4==s5 is true because we override the __eq__ function it will give true when the roll number is some
print(id(s4))
print(id(s5))
# object of class student
s6 = Student("David", 293)
# other object of class student
s7 = Student("David", 178)
# Applying equality function two objects will give us False because the roll is different
print(s6 == s7)
出力:
True
1935568125136 //(it will vary)
1935568124656 //(it will vary)
False
現在、roll が同じかどうかをチェックする if 条件を内部に配置することにより、__eq__() メソッドをオーバーライドしています。これが、Python で __eq__() メソッドをオーバーライドする方法です。