strange behavor....

Diez B. Roggisch deets at web.de
Sat Nov 13 15:14:12 CET 2010


alex23 <wuwei23 at gmail.com> writes:

> Tracubik <affdfsdfds... at b.com> wrote:
>> why the integer value doesn't change while the list value do?
>
> http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

Not the issue here. 

The reason the OP sees a difference that there is only one way to pass
parameters in python. There have been wars waged about the right name to
call them. 

What's happening is that in the function, the parameter names are bound
to the objects the caller passed in.

But these names only exist in the scope of the function. So re-binding
that name by doing e.g.

 a = 2

does not change the binding in the callers context.

So because of this, no change happens in change_integer. Because there
is no change to the integer itself. Actually, you can't even change an
integer in pyhon. They are immutable. 

  a = 2
  a += 10

will make a point to the integer-object with the value 12. But the "old"
2 and 10 still exist.

And that's where the differency in change_list is in. That gets passed a
reference to a _mutable_ object, a list. And if you mutatet that list,
you end up with a changed object in the callers context as well.

Diez



More information about the Python-list mailing list