Python 比较运算符之间没有隐含关系
我最近开始阅读 在第3.4节:特殊方法名称中,特别是关于比较运算符Python 比较运算符之间没有隐含关系,python,python-2.7,Python,Python 2.7,我最近开始阅读 在第3.4节:特殊方法名称中,特别是关于比较运算符对象。\uuuu eq\uuuuu(self,other)和对象。\uuu ne\uuuuuu(self,other)中说明了以下内容,这导致了一些混淆: 比较运算符之间没有隐含关系。x==y的真理并不意味着x=y为假。因此,在定义eq()时,还应定义ne(),以使操作符的行为符合预期 这句话到底是什么意思?x==y的真值怎么能不自动毫无疑问地转化为x的假值呢=y?“无隐含关系”意味着,当您使用“!=”时,如果您没有实现\uuu
对象。\uuuu eq\uuuuu(self,other)
和对象。\uuu ne\uuuuuu(self,other)
中说明了以下内容,这导致了一些混淆:
比较运算符之间没有隐含关系。x==y的真理并不意味着x=y为假。因此,在定义eq()时,还应定义ne(),以使操作符的行为符合预期
这句话到底是什么意思?
x==y
的真值怎么能不自动毫无疑问地转化为x的假值呢=y
?“无隐含关系”意味着,当您使用“!=”时,如果您没有实现\uuuu ne\uuuuuu
,它不会调用\uuu eq\uuuuu
并否定结果。它将使用从其父级继承的\uu ne\uu
方法。大多数情况下,这将解析为对象。_____
,它只检查引用的相等性
>>> class Fred:
... def __eq__(self, other):
... print "eq was called!"
... return False
...
>>> x = Fred()
>>> print x == 23
eq was called!
False
>>> #if eq and ne had an implied relationship,
>>> #we'd expect this next line to also print "eq was called!"
>>> print x != 23
True
>>> #... but it doesn't.
这也意味着你可以自由地定义\uuuuuueq\uuuuu
和\uuu ne\uuuuu
,在数学上似乎是矛盾的。Python不会握着你的手
>>> class Fred:
... def __eq__(self, other):
... return True
... def __ne__(self, other):
... return True
...
>>> x = Fred()
>>> print x == 23
True
>>> print x != 23
True
尽管它确实建议您应该以数学上合理的方式实现它们。上面的代码块是合法的,但不是明智的。“无隐含关系”意味着当您使用“!=”时,如果您没有实现\uuuu ne\uuuuu
,它不会调用\uuu eq\uuuu
并否定结果。它将使用从其父级继承的\uu ne\uu
方法。大多数情况下,这将解析为对象。_____
,它只检查引用的相等性
>>> class Fred:
... def __eq__(self, other):
... print "eq was called!"
... return False
...
>>> x = Fred()
>>> print x == 23
eq was called!
False
>>> #if eq and ne had an implied relationship,
>>> #we'd expect this next line to also print "eq was called!"
>>> print x != 23
True
>>> #... but it doesn't.
这也意味着你可以自由地定义\uuuuuueq\uuuuu
和\uuu ne\uuuuu
,在数学上似乎是矛盾的。Python不会握着你的手
>>> class Fred:
... def __eq__(self, other):
... return True
... def __ne__(self, other):
... return True
...
>>> x = Fred()
>>> print x == 23
True
>>> print x != 23
True
尽管它确实建议您应该以数学上合理的方式实现它们。上面的代码块是合法的,但不是明智的。这里有一个人为的示例,演示了将两者分离的一种可能用法
class Z7(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
def __ne__(self, other):
return self.x % 7 != other.x % 7
这让我们可以对两个对象进行三向区分:完全相等的数字(==
返回True
),等于模7的数字(==
和!=
返回False
),以及模7不相等的数字(!=
返回真
)
这不使用第四种可能性,其中
==
和=
两者都返回True
,我想不出有什么好用。这里有一个精心设计的示例,演示了将两者解耦的一种可能用法
class Z7(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
def __ne__(self, other):
return self.x % 7 != other.x % 7
这让我们可以对两个对象进行三向区分:完全相等的数字(==
返回True
),等于模7的数字(==
和!=
返回False
),以及模7不相等的数字(!=
返回真
)
这不使用第四种可能性,其中==
和=
两者都返回True
,我想不出有什么好用