gpt4 book ai didi

python - 创建自定义类QPointF

转载 作者:行者123 更新时间:2023-12-01 08:11:08 26 4
gpt4 key购买 nike

我想用计算欧几里德距离的方法创建我的类 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)

关于python - 创建自定义类QPointF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55244480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com