class Inner():
def __init__(self, x):
self.x = x
def __eq__(self, other):
if isinstance(other, Inner):
return self.x == other.x
else:
raise TypeError("Incorrect type to compare")
class Outer():
def __init__(self, y):
self.y = Inner(y)
def __eq__(self, other):
if isinstance(other, Outer):
return self.y == other.y
elif isinstance(other, Inner):
return self.y == other
else:
raise TypeError("Incorrect type to compare")
if __name__ == "__main__":
a = Outer(1)
b = Inner(1)
print(a == b) # ok no problem
print(b == a) # This will raise a type error
在示例中,我有内部和外部类。我无法控制Inner工具只是为了模拟情况。我只控制Outer的行为。我希望外部实例能够与内部实例(不仅仅是相等)进行比较。与给定的实现只有第一次比较工作,因为这是调用Outer的__eq__
方法允许与外部和内部实例进行比较,但第二个调用内部的__eq__
这将不允许与外部的比较 - 它不知道外部存在为什么要这么麻烦呢? 有没有办法让第二种比较工作,类似__radd__
等功能。 我知道例如在C++中用内联运算符定义解决这个问题,但我们在Python中没有这样的解决方案。Python中的'反转'比较运算符