我想在 Python 3.7 程序中创建一个简单的 Point2d 类,仅实现一些功能。我在一个 SO 答案中看到(我现在找不到)创建 Point 类的一种方法是重写complex
所以我写了这个:
import math
class Point2d(complex):
def distanceTo(self, otherPoint):
return math.sqrt((self.real - otherPoint.real)**2 + (self.imag - otherPoint.imag)**2)
def x(self):
return self.real
def y(self):
return self.imag
这有效:
In [48]: p1 = Point2d(3, 3)
In [49]: p2 = Point2d(6, 7)
In [50]: p1.distanceTo(p2)
Out[50]: 5.0
但当我这样做时,p3
是的实例complex
, not Point2d
:
In [51]: p3 = p1 + p2
In [52]: p3.distanceTo(p1)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-52-37fbadb3015e> in <module>
----> 1 p3.distanceTo(p1)
AttributeError: 'complex' object has no attribute 'distanceTo'
我的大部分背景都是 Objective-C 和 C#,所以我仍在尝试找出执行此类操作的 Python 方式。我是否需要重写要在 Point2d 类上使用的所有数学运算符?或者我的处理方式完全错误吗?
在这种情况下,我建议实施你的课程Point2d
从头开始。
如果你很懒,可以看看像 sympy 这样的库,其中包括Point
类和其他几何的东西https://docs.sympy.org/latest/modules/geometry/index.html https://docs.sympy.org/latest/modules/geometry/index.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)