mag*_*gu_ 9 python operator-overloading python-3.x
我想知道有一个不平等的运营商的原因python
.
以下剪辑:
class Foo:
def __eq__(self, other):
print('Equal called')
return True
def __ne__(self, other):
print('Not equal called')
return True
if __name__ == '__main__':
a = Foo()
print(a == 1)
print(a != 1)
print(not a == 1)
Run Code Online (Sandbox Code Playgroud)
输出:
Equal called
True
Not equal called
True
Equal called
False
Run Code Online (Sandbox Code Playgroud)
这实际上是否可能会引发很多麻烦:
A == B and A != B
Run Code Online (Sandbox Code Playgroud)
可以同时正确.此外,这在忘记实施时引入了潜在的缺陷__ne__
.
根据一个人的需要,有些情况是平等和不平等不相反; 但是,绝大多数情况下它们都是相反的,所以在Python 3中如果你没有指定__ne__
方法,Python会__eq__
为你反转方法.
如果您要编写代码以在Python 2和Python 3上运行,那么您应该同时定义它们.
归档时间: |
|
查看次数: |
3476 次 |
最近记录: |