nor*_*ien 1 python iteration overloading
我写了这段代码来说明问题。在代码本身下方,您可以看到控制台打印输出。
在我的程序中,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 += 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()
Run Code Online (Sandbox Code Playgroud)
结果:如果我使用__add__,值更改就会丢失。如果我手动添加向量 - 它们会保留下来。我缺少什么?实际上与这个问题有__add__什么关系吗?这是怎么回事?
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
Run Code Online (Sandbox Code Playgroud)
您的问题是因为您的__add__函数返回 a 的新实例,Polygon而不是实际更改实例的值。
return Vector((self.x + Other_Vector.x),(self.y + Other_Vector.y))
Run Code Online (Sandbox Code Playgroud)
应该是:
self.x += Other_Vector.x
self.y += Other_Vector.y
return self
Run Code Online (Sandbox Code Playgroud)
正如 Pynchia 指出的那样,这仅在您假设+=正在调用操作员时才有效。为了更好地适合所有类实现,显式定义__add__和__iadd__数据模型方法:
__add__对于像这样的事情c = b + a应该返回一个新实例之类的事情,因此您的原始代码就可以了。
__iadd__用于就地运算符+=,然后应该像我的代码一样返回自身。
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |