【发布时间】:2014-06-03 15:52:12
【问题描述】:
我正在学习我的第一门计算科学课程,我们刚刚了解了类实现和继承。特别是,我们刚刚介绍了方法覆盖以及我们定义的类如何默认继承自 object 超类。作为尝试这种特殊继承情况的示例之一,我使用了以下代码:
class A:
def __init__(self, i):
self.i = i
def __str__(self):
return "A"
# Commenting out these two lines to not override __eq__(), just use the
# default from our superclass, object
#def __eq__(self, other):
#return self.i == other.i
x = A(2)
y = A(2)
>>>print(x == y)
False
>>>print(x.__eq__(y))
NotImplemented
我期待来自(x == y) 的结果,因为据我所知__eq__() 的默认值是检查它们是否是相同的对象,而不用担心内容。 False、x 和 y 内容相同,但对象不同。不过第二个让我吃惊。
所以我的问题是:我认为 (x==y) 和 x.__eq__(y) 是同义词,并且拨打了完全相同的电话。为什么这些会产生不同的输出?为什么第二个条件返回NotImplemented?
【问题讨论】:
标签: python object inheritance superclass