您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

__eq__如何在Python中以什么顺序处理?

__eq__如何在Python中以什么顺序处理?

a == b表达式调用A.__eq__,因为它存在。其代码包括self.value == other。由于int不知道如何将自己与B进行比较,因此Python尝试调用B.__eq__以查看是否知道如何将自己与int进行比较。

如果您修改代码显示正在比较的值:

class A(object):
    def __eq__(self, other):
        print("A __eq__ called: %r == %r ?" % (self, other))
        return self.value == other
class B(object):
    def __eq__(self, other):
        print("B __eq__ called: %r == %r ?" % (self, other))
        return self.value == other

a = A()
a.value = 3
b = B()
b.value = 4
a == b

它会打印:

A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?
python 2022/1/1 18:30:31 有241人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶