首先Python中对象包含的三个基本要素,分别是:id(身份标识)、type(数据类型)和value(值)
判断身份是否相同使用is
,其实内部是调用了__cmp__
魔法方法
判断值是否相同使用==
,其实内部是调用了__eq__
魔术方法
class A(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __cmp__(self, other):
return id(self) == id(other)
a = A(1)
b = A(1)
print(id(a)) #34663952
print(id(b)) #34747056
print(a == b) #True
print(a is b) #False