I have 2 point classes with + operator overloading:
class Point2D:
x = 0
y = 0
def __add__(self, __other: "Point2D"):
return Point2D(self.x + __other.x, self.y + __other.y)
class Point3D(Point2D):
z = 0
def __add__(self, __other: "Point3D"):
return Point3D(self.x + __other.x, self.y + __other.y, self.z + __other.z)
I can add 2 points of the same type, but I also want to be able to add 2 points of different types, for example:
>>> print(Point2D(1, 2) + Point3D(0, 1, 2))
(1, 3, 2)
I tried overloading the operator again with a different type expected like this (inside the Point3D class):
def __add__(self, __other: "Point2D"):
return Point3D(self.x + __other.x, self.y + __other.y, self.z)
but it doesn't recognize them as 2 different functions and just chooses the last one (my guess is because expected type parameters are only a suggestion in python and in practice it's all just an object so it has the same function signature). Is there a way to do this without resorting to isinstance() cases inside the function?
ifto determine whether__otheris aPoint2DorPoint3Dand do the right hting.a + bwill always trya.__add__(b)first.b.__add__(a)only gets called if that first method call returnsNotImplemented(to say "I can't handle this"). So maybe Point2D should only handle addition with other Point2Ds, then Point3D takes over in mixed cases? See docs.python.org/3/reference/…Point3D.__radd__()to handlePoint2D + Point3D?Point2D.__add__so say "not for me", which @OP means an isinstance check.