我定义了一个Point类,其方法是围绕另一个点旋转:
def Rotate(self, origin, degrees):
d = math.radians(degrees)
O = origin
sin = math.sin(d)
cos = math.cos(d)
print ("original "+self.ToString())
self.x += -O.x
self.y += -O.y
print ("-origin "+self.ToString())
WX = self.x * cos -self.y * sin
WY = self.x * sin +self.y * cos
self = Point(WX,WY)
print ("-origin, after transform "+self.ToString())
self.x += O.x
self.y += O.y
print ("End of method "+self.ToString())然后,我对该方法进行如下测试:
test = [Point(100,100),Point(110,110)]
test[0].Rotate(test[1],10)
print ("outside of method" + test[0].ToString())print命令的输出显示,在方法结束时分配了所需的值,但随后进行了更改。
这一切为什么要发生?
打印输出:
original 100 100
-origin -10 -10
-origin, after transform -8.111595753452777 -11.584559306791382
End of method 101.88840424654722 98.41544069320862
outside of method-10 -10发布于 2017-08-06 22:30:31
在您的功能中,您可以这样写:
self = Point(WX,WY)然而,这在方法之外没有效果self.:现在有修改了本地变量。您不能以这种方式重新分配self。在更改局部变量self之后,self.x当然会指向新Point(..)的新x属性,但不会更改调用该方法的对象。
但是,您可以做的是将分配给字段。
self.x, self.y = WX, WY话虽如此,你可以让事情变得更紧凑:
def rotate(self, origin, degrees):
d = math.radians(degrees)
sin = math.sin(d)
cos = math.cos(d)
dx = self.x - origin.x
dy = self.y - origin.y
wx = dx * cos - dy * sin + origin.x
wy = dx * sin + dy * cos + origin.y
self.x = wx
self.y = wyhttps://stackoverflow.com/questions/45537209
复制相似问题