简体   繁体   中英

Variable changes for unknown reason

#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?

ps sorry if my english is bad

You change the value of point inside function someFunc when you call it in 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 point being passed in you could create a local variable inside someFunc .

Something like this:

def someFunc(a_point): # note new parameter name

    loc_point = point(a_point.x, a_point.y)  # new local point

    if loc_point.x > 14: loc_point.x = 14
    elif loc_point.x < 0: loc_point.x = 0

    if loc_point.y > 14: loc_point.y = 14
    elif loc_point.y < 0: loc_point.y = 0

    return loc_point

Also, it's probably best not to use point to both refer to your class and your parameter.

Calling someFunc() uses by-reference semantics, so that the object it modifies is exactly the object you called it with. It seems you were expecting by-value semantics, where the function gets a copy of the object it was passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM