I want to make a simple Point2d class in a Python 3.7 program that implements just a few features. I saw in an SO answer (that I can't find now) that one way to create a Point class was to override complex so I wrote this:
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
This works:
In [48]: p1 = Point2d(3, 3)
In [49]: p2 = Point2d(6, 7)
In [50]: p1.distanceTo(p2)
Out[50]: 5.0
But when I do this, p3 is instance of 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'
Most of my background is in Objective-C and C# so I'm still trying to figure out the pythonic way of doing things like this. Do I need to override all the math operators I want to use on my Point2d class? Or am I going about this completely the wrong way?