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

Overloading addition function and the result creates a new type of class

我需要重载加法函数,使其将第一个点和终点作为方程的左侧和右侧并输出方程。这就是我的代码现在的样子。我不确定如何涉及 class?

这一行
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))

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

  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'>

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

没有任何内容表明 __add__() 方法必须 return 与实例类型相同 — 这意味着您可以这样做:

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 class 将继承该方法(因此您可能需要修改它的版本)。