小编gog*_*oji的帖子

Python:x == y和x .__ eq__y()的情况返回不同的东西.为什么?

我正在学习我的第一个计算科学课程,我们刚刚学习了类实现和继承.特别是,我们刚刚介绍了方法覆盖以及我们定义的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
Run Code Online (Sandbox Code Playgroud)

我期待结果(x == y),因为我理解它的默认值__eq__()是检查它们是否是相同的对象,而不是担心内容.哪个是False,x并且y具有相同的内容但是是不同的对象.第二个让我感到惊讶.

所以我的问题:我认为(x==y)并且x.__eq__(y)是同义词并且完全相同.为什么这些会产生不同的输出?为什么第二次有条件的回归NotImplemented呢?

python inheritance object superclass

7
推荐指数
2
解决办法
125
查看次数

标签 统计

inheritance ×1

object ×1

python ×1

superclass ×1