创建自定义 class QPointF

Creation custom class QPointF

我想用计算欧氏距离的方法创建我的 class 点。点 class 继承自 QPointF class。但是当执行 add 或 mul 等操作时,结果不是 Point class,而是 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'>

是的,您必须覆盖方法 __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)