#it's python 3.2.3
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, point):
return self.x == point.x and self.y == point.y
def __str__(self):
return 'point(%s, %s)' % (self.x, self.y)
def someFunc(point):
if point.x > 14: point.x = 14
elif point.x < 0: point.x = 0
if point.y > 14: point.y = 14
elif point.y < 0: point.y = 0
return point
somePoint = point(-1, -1)
print('ONE: %s' % somePoint)
if somePoint == someFunc(somePoint):
print('TWO: %s' % somePoint)
變量的變化我看到有後第一打印() 但變量somePoint沒有somePoint變量賦值神奇地改變後如果聲明由於未知原因,
輸出這一計劃的應該是
ONE: point(-1, -1)
但它是
ONE: point(-1, -1)
TWO: point(0, 0)
任何人可以解釋我爲什麼somePoint後
if somePoint == someFunc(somePoint):
病情變化?
p.s.對不起,如果我的英語不好
您正在更改'somePoint'中的** mutable **變量。你會期待什麼? – JBernardo
而不是修改'someFunc'裏面的'somePoint',你應該創建一個新的點對象並返回它作爲比較。 –
@JBernardo可變性(這裏)與對象有關,而不是變量..變量恰好指定了正在被突變的(相同)對象。 – 2012-05-25 16:32:42