小编And*_*eas的帖子

如果一方继承另一方,__ eq__的执行顺序是什么?

__eq__如果比较的一侧是从另一侧继承的对象,我最近偶然发现了关于方法执行顺序的看似奇怪的行为。

在一个公认的学术示例中,我已经在Python 3.7.2中进行了尝试。通常,在进行相等性比较的情况下,如果第一个调用返回了a == b,我希望a.__eq__首先被b.__eq__调用NotImplemented。但是,如果ab属于同一类层次结构的一部分,则情况似乎并非如此。考虑以下示例:

class A(object):
  def __eq__(self, other):
    print("Calling A({}).__eq__".format(self))
    return NotImplemented

class B(A):
  def __eq__(self, other):
    print("Calling B({}).__eq__".format(self))
    return True

class C(object):
  def __eq__(self, other):
    print("Calling C({}).__eq__".format(self))
    return False

a = A()
b = B()
c = C()

print("a: {}".format(a)) # output "a: <__main__.A object at 0x7f8fda95f860>"
print("b: {}".format(b)) # output "b: <__main__.B object at 0x7f8fda8bcfd0>"
print("c: {}".format(c)) # output "c: <__main__.C object at …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

18
推荐指数
1
解决办法
814
查看次数

标签 统计

python ×1

python-3.x ×1