我们如何在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 教师闺蜜祝福语简短