python类的特殊方法是如何工作的?

2024-04-18 08:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一节细胞课

class Cell :
    def __init__(self,char):
        self.char=char
        self.image='_'

    def __str__(self):
        return self.image

    def __eq__(self,other):
        return self.image == other.image

    def __ne__(self,other):
        return not self.image == other.image

那么我有两个Cell对象a和b,为什么我可以使用“if a!=b:“比较这两个物体。b如何进入a并调用eq方法进行比较


Tags: 对象imageselfreturninitdefnotcell
3条回答

b无法进入。当使用操作符时,Python首先在左侧参数上查找magic方法。如果在那里定义了适当的magic方法,则调用它。如果它没有返回NotImplemented,那么这就是结果。如果该方法不存在(或返回NotImplemented),则在右侧参数上调用magic方法(对于算术运算符,右边的参数得到一个单独的方法,__radd__是右边的pf__add____rsub__表示__sub__,等等)

所以在您的版本中,它在a上调用__ne__,就这样。在b上永远不会调用magic方法

这种行为在the documentation中描述

if a == b等同于if a.__eq__(b)

同样地,说if a != b实际上是if a.__ne__(b)。这两种方法都返回布尔值

每个类都继承用于比较相等和不相等的默认特殊方法,但如果显式定义,则可以重写这些方法

其他答案是正确的

我只想提一下__ne__有一个与优先级相关的bug。应定义为:

return not (self.image == other.image)

最好表述为:

return not (self == other)

Don't Repeat Yourself

相关问题 更多 >