no pass-values calling?

Neil Cerutti mr.cerutti at gmail.com
Wed Jan 16 13:21:07 CET 2008


On Jan 15, 2008 10:09 PM, J. Peng <peng.kyo at gmail.com> wrote:
> Hello,
>
> I saw this statement in Core Python Programming book,
>
> All arguments of function calls are made by reference, meaning that
> any changes to these parameters within the function
> affect the original objects in the calling function.

Yes, that's generally correct. But you must be careful about what is
meant by "changes to parameters". Assigning a new value to a parameter
name (inside the function, a parameter is just a local variable) does
not change the original object--it only rebinds the local variable to
a new object.

In the following function, a is rebound with an assignment statement,
while b is mutated, i.e., changed, with an assignment statement.

def f(a, b):
    a = 12
    b.value = 14

Argument a will never be changed, while argument b will be. Python's
argument passing semantics are extremely simple. It's the assignment
statement that's tricky: some assignments mutate/change objects, and
some only rebind names.

> Does this mean there is not pass-values calling to a function in
> python? only pass-reference calling? Thanks!

Neither is quite true. Values are passed by binding parameter names to
their corresponding arguments. This is similar to pass-by-reference in
some cases (when the argument is mutated) but not in others (when the
argument is not mutated). Thinking of it as pass-by-reference may help
you to understand it, but bear in mind that Python's "references" may
be rebound to new objects, which is quite different from the usual
behavior of references.

-- 
Neil Cerutti <mr.cerutti+python at gmail.com>



More information about the Python-list mailing list