我想用方法创建类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'>
最佳答案
是的,您必须覆盖方法__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)