创建自定义类 QPointF

我想用计算欧几里得距离的方法创建我的类 Point。Point 类继承自 QPointF 类。但是在执行 add 或 mul 等操作时,结果不是 Point 类,而是 QPointF。如何解决?我应该覆盖所有魔术方法还是有其他解决方案?


from PyQt5.QtCore import QPointF



class Point(QPointF):

    def __init__(self, *args, **kwargs):

        super(QPointF, self).__init__(*args, **kwargs)


    def dist(self):

        return (self._p.x() * self._p.x() +

                self._p.y() * self._p.y()) ** 0.5


 a = Point(1, 2)

 b = Point(2, 3)

 print(a + b, type(a + b))


>> PyQt5.QtCore.QPointF(3.0, 5.0) <class 'PyQt5.QtCore.QPointF'>


慕码人2483693
浏览 241回答 1
1回答

杨魅力

是的,您必须覆盖方法__add__,__mul__并且__repr__:from PyQt5.QtCore import QPointFclass Point(QPointF):&nbsp; &nbsp; def dist(self):&nbsp; &nbsp; &nbsp; &nbsp; return (self._p.x() * self._p.x() + self._p.y() * self._p.y()) ** 0.5&nbsp; &nbsp; def __add__(self, other):&nbsp; &nbsp; &nbsp; &nbsp; return self.__class__(super(self.__class__, self).__add__(other))&nbsp; &nbsp; def __mul__(self, other):&nbsp; &nbsp; &nbsp; &nbsp; return self.__class__(super(self.__class__, self).__mul__(other))&nbsp; &nbsp; def __repr__(self):&nbsp; &nbsp; &nbsp; &nbsp; return "{}({}, {})".format(self.__class__.__name__, self.x(), self.y())if __name__ == '__main__':&nbsp; &nbsp; a = Point(1, 2)&nbsp; &nbsp; b = Point(2, 3)&nbsp; &nbsp; print(a, type(a))&nbsp; &nbsp; print(b, type(b))&nbsp; &nbsp; print(a + b, type(a + b))&nbsp; &nbsp; a += Point(10, 10)&nbsp; &nbsp; print(a, type(a))&nbsp; &nbsp; a += QPointF(10, 10)&nbsp; &nbsp; print(a, type(a))&nbsp; &nbsp; print(a*3, type(a*3))&nbsp; &nbsp; print("a: {}".format(a))&nbsp; &nbsp; l = [a, b]&nbsp; &nbsp; print(l)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python