[Python]isと==の違いとは?

python-is-equal

isは同一性の比較
==は等価性(同値性)の比較
を行います。

Python Version

Python 3.9.0

is


オブジェクト同士がメモリー内で同一の箇所を参照している場合Trueになります。
参照箇所の識別子はid()を使用すると取得できます。

サンプルコード

下準備

class Hoge:
    def __init__(self, name):
        self.name = name


hoge1 = Hoge('hoge')
hoge2 = hoge1
hoge3 = Hoge('hoge')

id()を使用して参照箇所の識別子を確認してみる

print(f'hoge1のid = {id(hoge1)}')
print(f'hoge2のid = {id(hoge2)}')
print(f'hoge3のid = {id(hoge3)}')

実行結果
hoge1とhoge2が同一箇所を指している

hoge1のid = 1532449598288
hoge2のid = 1532449598288
hoge3のid = 1532449598480

is==の判定結果を確認してみる

print(f'hoge1 is hoge2 → {hoge1 is hoge2}')
print(f'hoge1 is hoge3 → {hoge1 is hoge3}')

print(f'hoge1 == hoge2 → {hoge1 == hoge2}')
print(f'hoge1 == hoge3 → {hoge1 == hoge3}')

実行結果

同一のメモリの箇所を参照していたhoge1とhoge2のisTrueを示し、==の判定結果もTrueになっている

hoge1 is hoge2 → True
hoge1 is hoge3 → False
hoge1 == hoge2 → True
hoge1 == hoge3 → False

==

オブジェクトのクラスの__eq__()メソッドでTrueと判定される場合Trueになります。

サンプルコード

下準備

__eq__メソッドを実装
hoge1とhoge3はどちらもnameをhogeに設定

class Hoge:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        if type(self) is not type(other):
            return False
        return self.__dict__ == other.__dict__

hoge1 = Hoge('hoge')
hoge2 = hoge1
hoge3 = Hoge('hoge')

is==の判定結果を確認してみる

print(f'hoge1 is hoge2 → {hoge1 is hoge2}')
print(f'hoge1 is hoge3 → {hoge1 is hoge3}')

print(f'hoge1 == hoge2 → {hoge1 == hoge2}')
print(f'hoge1 == hoge3 → {hoge1 == hoge3}')

実行結果

hoge1とhoge3は異なるオブジェクトなのでisの判定結果はFalseだが、nameが同じなので__eq__メソッドでTrueとなり、==の判定結果もTrueとなっている

hoge1 is hoge2 → True
hoge1 is hoge3 → False
hoge1 == hoge2 → True
hoge1 == hoge3 → True

参考

https://docs.python.org/ja/3/library/functions.html#id

1 COMMENT

コメントを残す

メールアドレスが公開されることはありません。