问题描述
任何人都可以给我一个合理的理由:
A级(对象):
def __init __(self,a):
self.a = a
def __eq __(自我,其他):
返回self.a == other.a
s = A(3)
t = A(3)
Can anybody please give me a decent justification for this:
class A(object):
def __init__(self, a):
self.a = a
def __eq__(self, other):
return self.a == other.a
s = A(3)
t = A(3)
True
我花了很长时间来追踪一个程序中的错误,这个行为是由于这个行为造成的。
当然是!=运算符应该,如果
对象没有__ne__方法,检查是否定义了__eq__方法,如果是,
返回其否定?
实际上,这给我带来了一个更广泛的问题 - 为什么__ne__存在于
所有?当然,它完全不一致和不必要的是,
单独等于而不等于对象上的方法? a!= b应该只是一个简短的写作方式(a == b)。对于初学者(比如我自己)而言,这两个人可以给出一个不同答案的事实在我看来是完全不直观的,并且是一个巨大的b / b
陷阱。
True
I just spent a long, long time tracking down a bug in a program that
results from this behaviour.
Surely the != operator should, if no __ne__ method is present for
either object, check to see if an __eq__ method is defined, and if so,
return its negation?
Actually, that brings me to a wider question - why does __ne__ exist at
all? Surely its completely inconsistent and unnessecary to have
seperate equals and not equals methods on an object? a != b should just
be a short way of writing not (a == b). The fact the two can give a
different answer seems to me to be utterly unintuitive and a massive
pitfall for beginners (such as myself).
推荐答案
我同意这令人困惑。我甚至都不理解这种行为,直到我去查看它为止:
基本原理这种行为是在PEP 207 - Rich Comparisons:
就个人而言,当我想要我的对象时,我实现了__cmp__方法
可比,所以我从来没有遇到过这个问题。
Dave
I agree that it''s confusing. I didn''t even understand this behavior
myself until I went and looked it up:
http://docs.python.org/ref/customization.html
The rationale for this behavior is in PEP 207 -- Rich Comparisons:
http://python.fyxm.net/peps/pep-0207.html
Personally, I implement the __cmp__ method when I want my objects to be
comparable, so I''ve never run into this problem.
Dave
肯定阅读文档是一个避免
陷阱的好方法吗?
__lt __,__ le__(等)
版本2.1中的新功能。这些是所谓的丰富的比较。方法,
并且比下面的__cmp __()更喜欢比较运算符。
/.../
比较运营商之间没有隐含的关系。
x == y的真值并不意味着x!= y是假的。因此,在定义
__eq__时,还应该定义__ne__,以便操作符按预期运行
。
/。 ../
__cmp__
如果丰富的比较(见上文)没有定义,则通过比较操作调用
定义。如果self<返回负整数其他,零如果自我
==其他,如果自我是正整数>其他。 /.../
,其中__ne__无法从__eq__派生,
见:
< / F> 0
surely reading the documentation would be a great way to avoid
pitfalls?
http://docs.python.org/ref/customization.html
__lt__, __le__ (etc)
New in version 2.1. These are the so-called "rich comparison" methods,
and are called for comparison operators in preference to __cmp__() below.
/.../
There are no implied relationships among the comparison operators. The
truth of x==y does not imply that x!=y is false. Accordingly, when defining
__eq__, one should also define __ne__ so that the operators will behave
as expected.
/.../
__cmp__
Called by comparison operations if rich comparison (see above) is not
defined. Should return a negative integer if self < other, zero if self
== other, a positive integer if self > other. /.../
for a number of situations where __ne__ cannot be derived from __eq__,
see:
http://www.python.org/peps/pep-0207.html
</F>0
这篇关于令人讨厌的!=运算符的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!