我有一个Python类,可以让你初始化线条,有两个x-y坐标点。我也有一个函数可以将两条线相加,如下图。
class Line:
def __init__(self, x1, y1, x2, y2):
...
def __add__(self, other):
new_x1 = self.x1 + other.x1
new_y1 = self.y1 + other.y1
new_x2 = self.x2 + other.x2
new_y2 = self.y2 + other.y2
return Line(new_x1, new_y1, new_x2, new_y2)
我有非常相似的减法和乘法函数 它们和加法函数是一样的 只是里面的运算符号不同
我的问题是,有没有更好或更有效的方法来写这个?
稍微简洁一点。
class Line:
def __init__(self, x1, y1, x2, y2):
self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2
def operation(self, other, op):
new_x1 = op(self.x1, other.x1)
new_y1 = op(self.y1, other.y1)
new_x2 = op(self.x2, other.x2)
new_y2 = op(self.y2, other.y2)
return Point(new_x1, new_y1, new_x2, new_y2)
def __add__(self, other):
return self.operation(other, float.__add__)
def __sub__(self, other):
return self.operation(other, float.__sub__)
你可以利用相似性。如果你也定义了 __neg__
你会得到稍微容易的addsub实现,因为sub == -add。
class Line:
def __init__(self, x1, y1, x2, y2):
self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2
def __add__(self, other):
new_x1 = self.x1 + other.x1
new_y1 = self.y1 + other.y1
new_x2 = self.x2 + other.x2
new_y2 = self.y2 + other.y2
return Line(new_x1, new_y1, new_x2, new_y2)
def __sub__(self, other):
return self + (-other) # leverage __neg__
def __neg__(self):
return Line(-self.x1,-self.y1,-self.x2,-self.y2)
def __str__(self):
return f"({self.x1}/{self.y1})->({self.x2}/{self.y2})"
l = Line(0,0,10,10)
l2 = Line(5,5,.20,20)
print(l)
print(l2)
print(l-l2)
输出。
(0/0)->(10/10)
(5/5)->(0.2/20)
(-5/-5)->(9.8/-10)
但大多数情况下,这并没有什么意义 因为操作可能会因你的类所处的域而大相径庭。
@Blotosmeteks的答案中的操作是很好的。但是为了补充,你也可以这样做。
class Line:
def __init__(self, x1, y1, x2, y2):
self.x1, self.y1, self.x2, self.y2 = float(x1), float(y1), float(x2), float(y2)
def operation(self, other, op): # Removing the declarations on multiple lines here.
return Point(op(self.x1, other.x1), op(self.y1, other.y1),
op(self.x2, other.x2), op(self.y2, other.y2))
def __add__(self, other):
return self.operation(other, float.__add__)
def __sub__(self, other):
return self.operation(other, float.__sub__)