I have written this snippet of code to illustrate the problem. Below the code itself you can see the console printout.
In my program, Polygon class objects store vertex coordinates in a list of vectors pointing to each vertex. All the Translate() function has to do is iterate over each vector in the list and add the argument vector to each item. Simple, right?
The Vector class has its own overloaded __add__
function.
When I wrote and tested the code, I found out that members of that list change only while I'm iterating. As soon as it's done, all coordinates revert to their original values.
After I've discovered this problem, on a hunch I made another function - Manual_Translate(), which calculates vector components by hand (without calling 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 += Translation.x
point.y += Translation.y
print (point.x, point.y)
def Report (self):
for point in self.Points:
print (point.x, point.y) #printout from another loop
vertices = [[0,0],[0,100],[100,100],[100,0]]
Square = Polygon (vertices)
print ("A: we used __add__ function")
Square.Translate (Vector(115,139))
print ("")
Square.Report()
print ("\nB: we calculated vector sum by hand")
Square.Manual_Translate (Vector(115,139))
print ("")
Square.Report()
The result:
If I use __add__
, the value changes get lost. If I add vectors by hand - they stay. What am I missing? Does __add__
actually have anything to do with this problem, or not? What's going on?
A: we used __add__ function
115 139
115 239
215 239
215 139
0 0
0 100
100 100
100 0
B: we calculated vector sum by hand
115 139
115 239
215 239
215 139
115 139
115 239
215 239
215 139