#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)
I see that there is no somePoint variable assignment after first print()
but variable somePoint magically changes after if statement
Output of this program should be
ONE: point(-1, -1)
But it is
ONE: point(-1, -1)
TWO: point(0, 0)
Could anybody explain me why somePoint changes after
if somePoint == someFunc(somePoint):
condition?
p.s. sorry if my english is bad
You change the value of
pointinside functionsomeFuncwhen you call itin your if-statement, so I would expect the value to be (0,0) at the
end. The reason is that you are passing a reference (or “Pass By Object Sharing”) to the function and any changes to it are reflected later on. This is unlike the pass-by-value method were a local copy is automatically produced.
To avoid changing the original
pointbeing passed in you could create a local variable insidesomeFunc.Something like this:
Also, it’s probably best not to use
pointto both refer to your class and your parameter.