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)
In the example, I have an inner and outer class. I have no control over the fact that Internal Instruments simply wanted to mimic the situation. I control only external behavior. I want external instances to be able to compare with internal instances (and not just equality). Only the first comparison is performed with this implementation, because the call to the Outer __eq__ method is allowed for comparison with external and internal instances, and the second calls Inner __eq__ , which does not allow comparison with Outer - heck it doesn 'I know that Outer exists, why it should to implement it. Is there a way to get the second type of comparison to work, with something similar to __radd__ and such functions. I know, for example, in C ++ you enable this using the built-in operator definitions, but we donβt have them in Python.
source share