我有一个像这样的容器对象:
class foo(object):
def __init__(self,value):
self.value = value
def __eq__(self,other):
return self.value == other
我可以这样使用:
>>> var = foo(4)
>>> var == 4
True
>>> var == 3
False
>>> # So far so good
>>> var == foo(4)
True
>>> var == foo(3)
False
>>> # Huh
我的问题是:发生了什么让它神奇地“#34;只是工作&#34 ;? Python如何绑定==
内的__eq__
运算符,以便比较双方的value
成员?
答案 0 :(得分:6)
如果__eq__
方法返回给定参数的NotImplemented
,Python将反向尝试相同的测试。因此,x == y
会首先尝试x.__eq__(y)
,如果返回NotImplemented
单身,则会尝试y.__eq__(x)
。
这也适用于内部你的__eq__
方法;你基本上是在比较:
self.value == other
是:
4 == other
是:
4.__eq__(other)
返回NotImplemented
:
>>> var = foo(4)
>>> (4).__eq__(var)
NotImplemented
因此Python会尝试other.__eq__(4)
,而是返回True
。