我有一节细胞课
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方法进行比较
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
相关问题 更多 >
编程相关推荐