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

4

2 回答 2

4

point当您在 if 语句中调用内部函数时,您会更改内部函数的值someFunc,所以我希望最后的值是 (0,0)。原因是您将引用(或“传递对象共享”)传递给函数,并且稍后会反映对它的任何更改。这与按值传递的方法不同,它会自动生成本地副本。

为避免更改point传入的原始变量,您可以在someFunc.

像这样的东西:

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

此外,最好不要point同时引用您的类和参数。

于 2012-05-25T16:22:17.473 回答
2

调用someFunc()使用按引用语义,因此它修改的对象正是您调用它的对象。您似乎期待按值语义,其中函数获取它传递的对象的副本。

于 2012-05-25T16:32:12.270 回答