考虑主类
class point2D:
def __init__(x, y):
self.x = x
self.y = y
def __sub__(self, other):
return vector2D(self.x - other.x, self.y - other.y)
和子类:
class vector2D(point2D):
def __add__(self, other):
return vector2D(self.x + other.x, self.y + other.y)
现在我希望 +
运算符也能够添加 vector2D
和 point2D
对象并返回 point2D
对象。任何类之间的 -
运算符无论如何都会返回 vector2D
。如果您能帮助我了解是否/如何在 Python 3.*
中做到这一点,我将不胜感激。
最佳答案
您清楚地知道如何重载运算符。使用类型检查返回所需类型的对象或 NotImplemented在每种情况下。
关于python - 如何在Python中的两个不同类之间进行运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53310157/