如果我有my_object = object()Python中的代码,my_object除了它自己将等于什么?
我怀疑答案在于__eq__返回的默认对象的方法object().__eq__这个默认对象的实现是什么?
编辑:我正在使用Python 2.7,但我也对Python 3的答案感兴趣.请澄清您的答案是否适用于Python 2,3或两者.
roi*_*ppi 28
object().__eq__返回NotImplemented单例:
print(object().__eq__(3))
NotImplemented
Run Code Online (Sandbox Code Playgroud)
通过丰富比较的反身规则,当NotImplemented返回时,尝试"反射"操作.因此,如果您在RHS上有一个返回True该比较的对象,那么True即使LHS没有实现比较,您也可以获得响应.
class EqualToEverything(object):
def __eq__(self,other):
return True
ete = EqualToEverything()
ete == object() # we implemented `ete.__eq__`, so this is obviously True
Out[74]: True
object() == ete # still True due to the reflexive rules of rich comparisons
Out[75]: True
Run Code Online (Sandbox Code Playgroud)
python 2特定位:如果两个对象都没有实现__eq__,那么python会继续检查是否实现__cmp__.等效反身规则适用于此处.
class ComparableToEverything(object):
def __cmp__(self,other):
return 0
cte = ComparableToEverything()
cte == object()
Out[5]: True
object() == cte
Out[6]: True
Run Code Online (Sandbox Code Playgroud)
__cmp__ 在python 3中消失了.
在python 2和3中,当我们耗尽所有这些比较运算符时NotImplemented,最终的回退是检查身份.(a is b)
jon*_*rpe 19
object没有实现__eq__,所以回到默认比较id(x) == id(y),即它们是相同的对象实例(x is y)?
每次调用object()时my_object都会创建一个新实例,永远不会*比较等于除自身之外的任何内容.
这适用于2.x和3.x:
# 3.4.0
>>> object().__eq__(object())
NotImplemented
# 2.7.6
>>> object().__eq__(object())
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
object().__eq__(object())
AttributeError: 'object' object has no attribute '__eq__'
Run Code Online (Sandbox Code Playgroud)
*或者更确切地说,是roippi"的回答指出,未落,假设明智的__eq__其他地方实现.
| 归档时间: |
|
| 查看次数: |
2140 次 |
| 最近记录: |