重载加法函数,结果将创建一个新类型的类



我需要重载加法函数,使其将第一点和终点作为方程的左侧和右侧,并输出方程。这就是我的代码现在的样子。我不知道如何让线路类参与进来?

import math
class Point:
'''Class that creates points. Attributes: Eastings and Northings'''
def __init__(self,x,y):
self.eastings = x
self.northings = y
def getCoords(self):
self.coords = (self.eastings,self.northings)
return self.coords
def setCoords(self,other_x,other_y):
self.eastings = float(other_x)
self.northings = float(other_y)
def __str__(self):
return f"{self.eastings},{self.northings}"
def __add__(self,new_point):
pass
#creates a line (new class)

class Line(Point):
'''Class that creates line object based on two points'''
def __init__(self,start,end):
self.start = start #Type:Point (x1,y1)
self.end = end #Type:Point (x2,y2)
self.latitude = abs(self.end.eastings - self.start.eastings)
self.departure = abs(self.end.northings - self.start.northings)
self.distance = math.sqrt((self.latitude)**2 + (self.departure)**2)
self.azimuth = math.degrees(math.atan2(self.departure,self.latitude))
def __getitem__(self,key):
if key == 0:
ans = self.start
elif key == 1:
ans = self.end
else:
print("invalid index")
return ans
#test code
a = Point(0,0)
b = Point(1,1)
c = Point(1,0.5)
line1 = a+b
print((type(line1))

测试代码应该将类型打印为类行。

没有什么规定__add__()方法必须返回与实例相同的类型——这意味着你可以这样做:

class Point:
...
def __add__(self, other):
if isinstance(other, Point):
return Line(self, other)  # Line from this Point to the other.
else:
raise TypeError(f"Can't add a non-Point to a Point}")

但是,这样做要小心,因为Line类将继承该方法(因此您可能需要修改它的版本(。

  1. Point.__init__()方法添加self.getCoords()调用。

  2. return Line(self, new_point)添加到Point.__add__()方法中。

测试:

a = Point(0,0)
b = Point(1,1)
c = Point(1,0.5)
line1 = a+b
print(type(line1)) # I have removed a round bracket on the left

输出:<class '__main__.Line'>

如果你想运行一个代码块,其中一个函数/方法没有一行,你必须向它添加一个pass。否则你会得到一个错误,因为结构需要它。或者你注释掉函数声明。

最新更新