python – 设置“in”运算符:使用相等或身份?
作者:互联网
class A(object):
def __cmp__(self):
print '__cmp__'
return object.__cmp__(self)
def __eq__(self, rhs):
print '__eq__'
return True
a1 = A()
a2 = A()
print a1 in set([a1])
print a1 in set([a2])
为什么第一行打印为True,但第二行打印为False?既不进入操作符eq?
我使用的是Python 2.6
解决方法:
您还需要定义__hash__
.例如
class A(object):
def __hash__(self):
print '__hash__'
return 42
def __cmp__(self, other):
print '__cmp__'
return object.__cmp__(self, other)
def __eq__(self, rhs):
print '__eq__'
return True
a1 = A()
a2 = A()
print a1 in set([a1])
print a1 in set([a2])
将按预期工作.
作为一般规则,每当你实现__cmp__
时,你应该实现一个__hash__,这样对于所有x和y,使得x == y,x .__ hash __()== y .__ hash __().
标签:python,identity,set,equality,operator-keyword 来源: https://codeday.me/bug/20190927/1824786.html