[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: assignment, reference, += and parameter passing

Pixel <pixel@mandrakesoft.com> writes:

> Python
>   pass-by-ref except for numbers and strings

You misunderstand Python's assignment and parameter passing model.

It is always "pass by object reference".

All names are bound to object references.  Parameters are
bound by object references.  The value in the object has absolutely
nothing to do with this.  In this way "=" and parameter passing are
basically equivalent.

Numbers and strings are passed in exactly the same way as are lists,
class instances, or anything else.  They are simply the content of an
object that is being referenced.

The source of your confusion may be that "=" and "+=" operate in a
very different way from each other.  (In my opinion "+=" should not
have been added, precisely because of this confusion.)

a = b 

  This always binds a to refer to the same object as b.

def f(x):
    do something with x

  This always binds x to refer to the same object as a, regardless of
  the type of the value in that object.

a += b

  This is a bit funny.  Generally, if a refers to a mutable object such
  as a list, this modifies the existing object that a refers to.  If a
  refers to an immutable object such as an int, this rebinds a to
  refer to a new object obtained by adding a and b.