我写了这段代码来说明问题。在代码本身下方,您可以看到控制台打印输出。
在我的程序中,Polygon 类对象将顶点坐标存储在指向每个顶点的向量列表中。Translate() 函数所要做的就是迭代列表中的每个向量并将参数向量添加到每个项目。很简单,对吧?
Vector 类有自己的重载__add__函数。
当我编写和测试代码时,我发现该列表的成员仅在我迭代时才会更改。完成后,所有坐标都会恢复为原始值。
在我发现这个问题之后,凭直觉我做了另一个函数 - Manual_Translate(),它手动计算向量分量(不调用 Vector。__add__)
class Vector():
def __init__(self, X, Y):
self.x = X
self.y = Y
def __add__(self, Other_Vector):
return Vector((self.x + Other_Vector.x),(self.y + Other_Vector.y))
class Polygon():
def __init__(self, point_list):
self.Points = []
for item in point_list:
self.Points.append (Vector(item[0], item[1]))
def Translate (self, Translation):
for point in self.Points:
point += Translation
print (point.x, point.y) #printout from the same loop
def Manual_Translate (self, Translation):
for point in self.Points:
point.x += …Run Code Online (Sandbox Code Playgroud)