创建自定义类QPointF

问题描述 投票:1回答:1

我想创建我的类Point with method来计算欧几里德距离。 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'>
python class pyqt point
1个回答
1
投票

是的,你必须覆盖方法__add____mul____repr__

from PyQt5.QtCore import QPointF

class Point(QPointF):
    def dist(self):
        return (self._p.x() * self._p.x() + self._p.y() * self._p.y()) ** 0.5

    def __add__(self, other):
        return self.__class__(super(self.__class__, self).__add__(other))

    def __mul__(self, other):
        return self.__class__(super(self.__class__, self).__mul__(other))

    def __repr__(self):
        return "{}({}, {})".format(self.__class__.__name__, self.x(), self.y())

if __name__ == '__main__':
    a = Point(1, 2)
    b = Point(2, 3)
    print(a, type(a))
    print(b, type(b))
    print(a + b, type(a + b))
    a += Point(10, 10)
    print(a, type(a))
    a += QPointF(10, 10)
    print(a, type(a))
    print(a*3, type(a*3))
    print("a: {}".format(a))
    l = [a, b]
    print(l)
© www.soinside.com 2019 - 2024. All rights reserved.