对象值从什么是在方法
问题描述:
分配不同予定义与方法的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())
输出的打印命令显示在方法结束时分配了所需的值,但之后发生了变化。
为什么会发生这种情况?
打印输出:
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
答
在你的函数你写:
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 = wy
分配'自我=点(WX, WY)'。而self是一个* local *变量。 –
我建议你查看[数据模型](https://docs.python.org/3/reference/datamodel.html) - 'ToString'使它看起来像你正在写Java([Python不是](http://dirtsimple.org/2004/12/python-is-not-java.html))。你能给工人上一堂[mcve]吗? – jonrsharpe