Python 对象比较(is & ==)

Python 对象有 3 要素

  1. id
  2. type
  3. value

id

对象在内存中的地址
可以通过 id() 获取

比较

只有同一个对象 id 才会相同
id 通过 is 比较
示例:

a = list()
b = a
c = list()
print(a is b)
print(a is c)

输出结果:

True
False

type

对象的种类
可以通过 type() 获取

比较

type 通过 isinstance 比较

a = list()
b = list()
print(isinstance(a, type(b)))

输出结果:

True

value

对象的值

比较

value 通过 == 比较
示例:

a = list()
b = list()
print(a == b)
print(a is b)

输出结果:

True
False

相当于 __eq__()
示例:

a = list()
b = list()
print(a.__eq__(b))

输出结果:

True
原文地址:https://www.cnblogs.com/dbf-/p/11864616.html