Python 对象比较(is & ==)

Python 对象有 3 要素code

  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)

输出结果:class

True
False

type

对象的种类
能够经过 type() 获取co

比较

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
相关文章
相关标签/搜索