我们如何在Python类中使用等价(“相等”)运算符?
如果使用下面的代码中的相等运算符,则输出为false
class Integer:
def __init__(self, number):
self.number = number
n1 = Integer(1)
n2 = Integer(1)
print bool(n1 == n2)输出结果
False
这是因为默认情况下,Python使用对象标识符进行比较操作:
为了克服这个问题,我们必须重写__eq__function
class Integer:
def __init__(self, number):
self.number = number
def __eq__(self, other):
if isinstance(self, other.__class__):
return self.__dict__ == other.__dict__
return False
n1 = Integer(1)
n2 = Integer(1)
print bool (n1 == n2)
print bool (n1 != n2)输出结果
True True
对于Python2.x,我们还必须覆盖__ne__函数。对于Python3.x,这不是必需的。根据文档,以下内容适用。
默认情况下,除非未实现,否则__ne__()委托给__eq__()并反转结果。比较运算符之间没有其他隐含关系,例如,(x<y或x==y)的真相并不意味着x<=y。
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志